<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/11
 * Time: 14:25
 */

namespace App\Http\Controllers\Admin;

use App\Model\Apply;
use App\Model\ExceedShop;
use App\Model\FieldActivities;
use App\Model\IdentityVerification;
use App\Model\MembersLevel;
use App\Model\MicroMall;
use App\Model\Poundage;
use App\Model\Prize;
use App\Model\Retreat;
use App\Model\SetBonus;
use App\Model\SetQuality;
use App\Model\SetRebate;
use App\Model\SetrebateCompany;
use App\Model\ShopGoodsClassify;
use App\Model\StoresProfitRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Model\Members;
use App\Model\Transaction;
use App\Model\RecordrRecharge;
use App\Model\RecordBonus;
use App\Model\StoresCenter;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\Address;
use App\Model\ShopGoods;
use App\Model\RecordTransaction;
use Auth;
use Excel;
use Log;
use DB;
use Session;

ini_set('max_execution_time', 0);

class MemberController extends BaseController
{
    /**
     * 会员首页
     */
    public function index()
    {
//

        return view('Admin.member');
    }

    /**
     * 代理商
     */
    public function apply()
    {
        return view('Admin.apply');
    }

    /**
     * 代理商
     */
    public function phonePay()
    {
        return view('Admin.phonePay');
    }
    /**
     *我的伙伴
     */


    /*
        public function myPartners(Request $request)
        {
            $name = $request->get('name');
            if (empty($name)) {
                return view('Admin.myPartners', ['data' => '', 'edges' => '','names'=>'']);
            } else {
                $userUid = Members::where('phone',$name)->select('uid')->first();
                $useInfo = Members::where('uid',$userUid['uid'])->first();
                $userData = Members::where('referrer',$userUid['uid'])->get();
                $data = [];
                $edges = [];
                foreach ($userData as $key => $value) {
                    $uid[0] = $value['uid'];
                    $Alluser = Members::where('uid','>', $value['uid'])->get();
                    $this->PartnersNum($Alluser, $uid,0);
                    $pid = session('pid');
    //                $money = session('money');
                    $data[$key]['id'] = $value['uid'];
                    $data[$key]['label'] = $value['user_name']."\n".$value['name'] . "\n".$pid;
                    $edges[$key]['from'] = $value['referrer'];
                    $edges[$key]['to'] = $value['uid'];
                }
                array_push($data, ['id' => $userUid['uid'], 'label' => $useInfo['user_name'] . "\n" . $useInfo['name']]);

                $data = json_encode($data, true);
                $edges = json_encode($edges, true);
                return view('Admin.myPartners', ['data' => $data, 'edges' => $edges,'names'=>$name]);
            }


        }
    */


    public function myPartners(Request $request)
    {
        $name = $request->get('name');
        if (empty($name)) {
            return view('Admin.myPartners', ['data' => '', 'edges' => '', 'names' => '']);
        } else {
            $userUid = Members::where('name', $name)->select('uid')->first();
            if (empty($userUid)) return view('Admin.myPartners', ['data' => '', 'edges' => '', 'names' => '']);
            $useInfo = Members::where('uid', $userUid['uid'])->first();
            $userData = Members::where('referrer', $userUid['uid'])->get(['uid', 'user_name', 'referrer', 'name'])->toArray();
            $data = [];
            $edges = [];
            foreach ($userData as $key => $value) {
                $uid[0] = $value['uid'];
                $Alluser = Members::where('uid', '>', $value['uid'])->get(['referrer', 'uid', 'original_money'])->toArray();
                $this->PartnersNum($Alluser, $uid, 0);
                $pid = session('pid');
//                $money = session('money');
                $data[$key]['id'] = $value['uid'];
                $data[$key]['label'] = $value['user_name'] . "\n" . $value['name'] . "\n" . $pid;
                $edges[$key]['from'] = $value['referrer'];
                $edges[$key]['to'] = $value['uid'];
            }
            array_push($data, ['id' => $userUid['uid'], 'label' => $useInfo['user_name'] . "\n" . $useInfo['name']]);

            $data = json_encode($data, true);
            $edges = json_encode($edges, true);
            return view('Admin.myPartners', ['data' => $data, 'edges' => $edges, 'names' => $name]);
        }

        // return view('Admin.myPartners',['data' => $data, 'edges' => $edges,'names'=>$name]);
    }

    /**
     * 开通超级商城
     */
    public function openShop(Request $request)
    {
        $userUid = $request->get('id');
        $userDatas = Members::where('uid', $userUid)->first();
        if ($userDatas['isdown'] == 1) {
            return ['code' => 0, 'data' => '已经开通'];
        } else {
            $userData = Members::where('referrer', $userUid)->get();
            $super_recommend = count($userData);//直推人数
            $data = [];
            foreach ($userData as $key => $value) {
                $uid[0] = $value['uid'];
                $Alluser = Members::where('uid', '>', $value['uid'])->get();
                $this->PartnersNum($Alluser, $uid, 0);
                $pid = session('pid');
                $money = session('money');
                $data[$key]['id'] = $value['uid'];
                $data[$key]['name'] = $value['user_name'];
                $data[$key]['number'] = $pid;
                $data[$key]['money'] = $money;
            }
            $super['super_recommend'] = 0; //超级商城 推荐人数
            $super['super_team_count'] = 0; //团队数量
            $super['isdown'] = 1; //'超级商城开关 1开 2关
            $counts = 0; //小区人数
            $counts_money = 0; //小区总额
            $big_num = 0; //大区人数
            $big_num_money = 0; //大区总额
            $super_team_count_money = 0;
            if ($data) {
                //排序
                $arrSort = array();
                foreach ($data as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                array_multisort($arrSort['number'], constant('SORT_DESC'), $data);
                foreach ($data as $items => $item) { //上级V3
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['number'];
                        $counts_money += $item['money'];
                    } else {
                        $big_num = $item['number'];
                        $big_num_money = $item['money'];
                    }
                }
                $super_team_count = $counts + $big_num; //总人数
                $super_team_count_money = $counts_money + $big_num_money; //总人数
                $super['super_recommend'] = $super_recommend; //超级商城 推荐人数
                $super['super_team_count'] = $super_team_count; //团队数量
            }
            if ($super_recommend > 9) {
                if ($counts_money >= 90000 && $big_num_money >= 90000) {
                    $super['super_level_name'] = 'V3'; //更改等级名字
                    $super['super_level'] = 3;//更改等级
                } else {
                    if ($super_team_count_money > 36000) {
                        $super['super_level_name'] = 'V2'; //更改等级名字
                        $super['super_level'] = 2;//更改等级
                    } else {
                        $super['super_level_name'] = 'V1'; //更改等级名字
                        $super['super_level'] = 1;//更改等级
                    }
                }
            } else {
                $super['super_level_name'] = 'V1'; //更改等级名字
                $super['super_level'] = 1;//更改等级
            }

            $rico = Members::where('uid', $userUid)->update($super);
            if ($rico) {
                return ['code' => 1, 'data' => '开通成功'];
            } else {
                return ['code' => 0, 'data' => '开通失败'];
            }
        }

    }

    /**
     *统计数量
     */

    public function PartnersNum($data = array(), $uid = array(), $pid = 0, $moeny = 0)
    {
        $nodesid = [];
        foreach ($data as $k => $v) {
            foreach ($uid as $key => $value) {
                if ($v['referrer'] == $value) {
                    $pid = empty($pid) ? 1 : $pid + 1;
                    $nodesid[] = $v['uid'];
                    $moeny = empty($moeny) ? $v['original_money'] : $moeny + $v['original_money'];
                }
            }
        }
        if (!empty($nodesid)) {
            $this->PartnersNum($data, $nodesid, $pid, $moeny);
        } else {
            //保存session
            Session::put('pid', $pid);
            Session::put('money', $moeny);
        }
    }


    /*
    * 个人购买面膜奖励
    */
    public function getTotal(Request $request)
    {
        $data = $request->all();
        if ($data['uid']) {
            $record = Members::where('uid', $data['uid'])
                ->select(
                    'dnum', 'num', 'total'
                )
                ->first();
            if ($record['num'] == '') {
                $record['num'] = 0;
            }
            if ($record['total'] == '') {
                $record['total'] = '0.00';
            }
            if ($record['dnum'] == '') {
                $record['dnum'] = 0;
            }
            if ($record) {
                return ['code' => 1, 'data' => $record];
            } else {
                return ['code' => 0, 'data' => "没有数据"];
            }
        }

    }


    /**
     * 记录订单之前各会员的奖励币余额记录
     * @param int $uid 用户ID
     * @param string $ordersn 统一订单
     * @return array
     */
    public function credit2Record($ordersn, $uid)
    {
        $ShopOrder = new ShopOrder();
        $UserModel = new Members();
        $orderMemberCredit2Datas = [];
        $orderMemberCredit2Uid = [];
        $orderMemberCredit2Uids = [];
        $memberLastCredit2Data = $ShopOrder->where(['ordersn' => $ordersn])->value('last_credit2s');
        if ($memberLastCredit2Data != "") {
            $memberLastCredit2Data = unserialize($memberLastCredit2Data);
        } else {
            $memberLastCredit2Data = [];
        }
        $memberLastCredit2 = [];
        $memberLastData = $UserModel->where(['uid' => $uid])->select('uid', 'name', 'user_name', 'credit1', 'credit2', 'credit4', 'voucher')->first();
        $memberLastCredit2['uid'] = $memberLastData['uid'];
        $memberLastCredit2['name'] = $memberLastData['name'];
        $memberLastCredit2['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2['credit4'] = $memberLastData['credit4'];
        $memberLastCredit2['voucher'] = $memberLastData['voucher'];

        if ($memberLastCredit2Data) {
            foreach ($memberLastCredit2Data as $key => $value) {
                array_push($orderMemberCredit2Uid, $value['uid']);
            }
            if (!in_array($uid, $orderMemberCredit2Uid)) {
                array_push($memberLastCredit2Data, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($memberLastCredit2Data);
        } else {
            if (count($orderMemberCredit2Datas) > 0) {
                foreach ($orderMemberCredit2Datas as $key => $value) {
                    array_push($orderMemberCredit2Uids, $value['uid']);
                }
                if (!in_array($uid, $orderMemberCredit2Uids)) {
                    array_push($orderMemberCredit2Datas, $memberLastCredit2);
                }
            } else {
                array_push($orderMemberCredit2Datas, $memberLastCredit2);
            }
            $Credit2SaveData = serialize($orderMemberCredit2Datas);
        }
        $ShopOrder->where(['ordersn' => $ordersn])->update(['last_credit2s' => $Credit2SaveData]);
    }


    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null, $money = null, $type = null, $explain = '', $manageMoney = array(), $company_id = null, $ordersn = '')
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $money,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain . '：' . $manageMoney['money'] . '，复销：' . $manageMoney['redelivery'] . '，平台费：' . $manageMoney['platform_fee'],
            'time' => time(),
            'company_id' => $company_id,
        ];
        $RecordBonus->add_bonus($bonusData);
    }


    /**
     * 微商城奖金计算
     * @param null $uid 会员id
     * @param null $referrer 分享人
     * @param array $micro 微商城设置
     * @param array $Poundage 系统设置
     * @param null $money 金额
     * @param int $company_id 分公司id
     * @param string $upgrade 等级
     * @param string $ordersn 统一订单
     */
    public function bonusMicro($uid = null, $referrer = null, $micro = array(), $Poundage = array(), $money = null, $company_id = 0, $upgrade = '', $ordersn = '')
    {
        //会员表
        $UserModel = new Members();
        $ShopOrder = new ShopOrder();
        $referrer = $referrer; //分享人
        $money1 = $money; //微客
        $money2 = $money; //创客
        $money3 = $money; //品牌创客
        $money4 = $money; //股东创客
        $number1 = 1; //微客次数
        $number2 = 1; //创客次数
        $number3 = 1; //品牌创客次数
        $number4 = 1; //股东创客次数
        $maker1 = 1; //微客分奖3次
        $maker2 = 1; //创客分奖3次
        $maker3 = 1; //品牌分奖3次
        $maker4 = 1; //股东分奖3次

        $members = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'credit1', 'credit2', 'credit4', 'credit5', 'tiny_level', 'complex_money', 'maker_team', 'shareholder_team', 'type')->get()->toArray();
        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) { //寻找上级id 微客
                    $referrer = $v['referrer'];
                    if ($upgrade == 2) { //创客
                        $v['maker_team'] += 1;
                    } elseif ($upgrade == 3) { //品牌
                        $v['shareholder_team'] += 1;
                    }
                    //三级微客
                    if ($maker1 <= 3) {
                        //微客
                        if ($number1 == 1) { //当$number1 等于1的时候就拿分享奖
                            $money1 = RETAIN_TWO($money * ($micro[0]['conditions'] * 0.01));
                            $recommendMoney = CALCULATE($Poundage, $money1);
                            ++$number1;
                            ++$maker1;
                            //添加记录
                            if ($v['type'] == 1) {
                                $v['credit2'] += $recommendMoney['money'];
                                $v['credit5'] += $recommendMoney['redelivery'];
                                $this->bonusCredit2($v['uid'], $ordersn);
                                $this->addOrder($v['uid'], $money1, 5, '微客分享奖', $recommendMoney, $company_id, $ordersn);
                            }

                        } else {
                            if ($money1 > 1) {
                                $money1 = RETAIN_TWO($money1 * ($micro[0]['management'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money1);
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    //添加记录
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money1, 5, '微客管理奖', $recommendMoney, $company_id, $ordersn);
                                }
                                ++$maker1;
                            }
                        }
                    }
                    //三级创客
                    if ($maker2 <= 3) {
                        //创客
                        if ($v['tiny_level'] >= 2) {
                            if ($number2 == 1) { //当$number1 等于1的时候就拿分享奖
                                //$micro[1]['conditions']- $micro[0]['conditions'] 减去已经拿的分享奖
                                $money2 = RETAIN_TWO($money * (($micro[1]['conditions'] - $micro[0]['conditions']) * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money2);
                                ++$number2;
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money2, 5, '创客分享奖', $recommendMoney, $company_id, $ordersn);
                                }
                                ++$maker2;
                            } else {
                                if ($money2 > 1) {
                                    $money2 = RETAIN_TWO($money2 * ($micro[1]['management'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money2);
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        //添加记录
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money2, 5, '创客管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                    ++$maker2;
                                }
                            }
                        }
                    }
                    //三级品牌
                    if ($maker3 <= 3) {
                        //品牌
                        if ($v['tiny_level'] >= 3) {
                            if ($number3 == 1) { //当$number1 等于1的时候就拿分享奖
                                //$micro[2]['conditions']- $micro[1]['conditions'] 减去已经拿的分享奖
                                $money3 = RETAIN_TWO($money * (($micro[2]['conditions'] - $micro[1]['conditions']) * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money3);
                                ++$number3;
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //添加记录
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money3, 5, '品牌分享奖', $recommendMoney, $company_id, $ordersn);
                                }
                                ++$maker3;
                            } else {
                                if ($money3 > 1) {
                                    $money3 = RETAIN_TWO($money3 * ($micro[2]['management'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money3);
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        //添加记录
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money3, 5, '品牌管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                    ++$maker3;
                                }
                            }
                        }
                    }
                    //三级股东
                    if ($maker4 <= 3) {
                        //股东
                        if ($v['tiny_level'] >= 4) {
                            if ($number4 == 1) { //当$number1 等于1的时候就拿分享奖
                                //$micro[2]['conditions']- $micro[1]['conditions'] 减去已经拿的分享奖
                                $money4 = RETAIN_TWO($money * (($micro[3]['conditions'] - $micro[2]['conditions']) * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money4);
                                ++$number4;
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];

                                    //添加记录
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money4, 5, '股东分享奖', $recommendMoney, $company_id, $ordersn);
                                }
                                ++$maker4;
                            } else {
                                if ($money4 > 1) {
                                    $money4 = RETAIN_TWO($money4 * ($micro[3]['management'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money4);
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        //添加记录
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money4, 5, '股东管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                    ++$maker4;
                                }
                            }
                        }
                    }
                }
                //更新会员数据
                $UserModel->where(['uid' => $v['uid']])->update($v);
            }
        }
    }

    /**
     * 微商城会员订单之前的奖金币金额记录
     * @param null $uid 会员id
     * @param string $ordersn 统一订单
     */
    public function bonusCredit2($uid, $ordersn)
    {
        $UserModel = new Members();
        $ShopOrder = new ShopOrder();
        $memberLastCredit2Datas = $ShopOrder->where(['ordersn' => $ordersn])->value('last_credit2s');
        if ($memberLastCredit2Datas) {
            $memberLastCredit2Datas = unserialize($memberLastCredit2Datas);
        } else {
            $memberLastCredit2Datas = [];
        }
        $memberLastCredit2Id = [];
        $memberLastCredit2 = [];
        $memberLastCredit2Data = [];
        $memberLastData = $UserModel->where(['uid' => $uid])->select('uid', 'name', 'user_name', 'credit1', 'credit2', 'credit4')->first();
        $memberLastCredit2Data['uid'] = $memberLastData['uid'];
        $memberLastCredit2Data['name'] = $memberLastData['name'];
        $memberLastCredit2Data['user_name'] = $memberLastData['user_name'];
        $memberLastCredit2Data['credit1'] = $memberLastData['credit1'];
        $memberLastCredit2Data['credit2'] = $memberLastData['credit2'];
        $memberLastCredit2Data['credit4'] = $memberLastData['credit4'];

        if ($memberLastCredit2Data) {
            if ($memberLastCredit2Datas && count($memberLastCredit2Datas) > 0) {
                foreach ($memberLastCredit2Datas as $key => $value) {
                    if (!in_array($value['uid'], $memberLastCredit2Id)) {
                        array_push($memberLastCredit2Id, $value['uid']);
                    }
                }
            }
            if (!in_array($uid, $memberLastCredit2Id)) {
                array_push($memberLastCredit2Datas, $memberLastCredit2Data);
                array_push($memberLastCredit2Id, $uid);
            }
        }
        if ($memberLastCredit2Datas) {
            $ShopOrder->where(['ordersn' => $ordersn])->update(['last_credit2s' => serialize($memberLastCredit2Datas)]);
        }


    }

    /**
     * 区域代理分红
     * @param int $money 支付金额
     * @param int $company_id 分公司id
     * @param array $Poundage 系统设置
     * @param null $province 省
     * @param null $city 市
     * @param null $area 区
     * @param string $ordersn 统一订单
     * @return array
     */
    public function agency($money = 0, $company_id = 0, $Poundage = array(), $province = null, $city = null, $area = null, $ordersn = '')
    {
        if ($money < 0 || empty($money)) {
            return ['code' => 0, 'data' => '参数错误'];
        }
        //会员表
        $UserModel = new Members();
        //查询代理区域
        $userApply = new Apply();
        //省
        $userProvince = $userApply->where(['type' => 0, 'province' => $province, 'status' => 1])->first();
        if ($userProvince) {
            //计算金额
            $provinceMoney = RETAIN_TWO($money * ($Poundage['province'] * 0.01));
            //扣除平台费和复投币
            $recommendMoney = CALCULATE($Poundage, $provinceMoney);
            $member = $UserModel->find_members(['uid' => $userProvince['uid']], ['uid', 'credit1', 'credit2', 'credit3', 'credit4']);
            if ($member) {
                $member['credit2'] += $recommendMoney['money'];
                $member['credit3'] += $recommendMoney['redelivery'];
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record($ordersn, $member['uid']);
                //更新会员数据
                $userAttributes = $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);
                if ($userAttributes) {
                    //添加记录
                    $this->addOrder($member['uid'], $provinceMoney, 5, '省代理分润', $recommendMoney, $company_id, $ordersn);
                }
            }
        }
        //市
        $userCity = $userApply->where(['type' => 1, 'city' => $city, 'status' => 1])->get();
        if ($userCity) {
            //计算金额
            $cityMoney = RETAIN_TWO($money * ($Poundage['city'] * 0.01));
            //扣除平台费和复投币
            $recommendMoney = CALCULATE($Poundage, $cityMoney);
            $uid = '';
            foreach ($userCity as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($area, $district)) {
                        $uid = $userCity[$k]['uid'];
                    }
                } else {
                    $uid = $v['uid'];
                }
            }
            $member = $UserModel->find_members(['uid' => $uid], ['uid', 'credit1', 'credit2', 'credit3', 'credit4']);
            if ($member) {
                $member['credit2'] += $recommendMoney['money'];
                $member['credit3'] += $recommendMoney['redelivery'];
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record($ordersn, $member['uid']);
                //更新会员数据
                $userAttributes = $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);
                if ($userAttributes) {
                    //添加记录
                    $this->addOrder($member['uid'], $cityMoney, 5, '市代理分润', $recommendMoney, $company_id, $ordersn);
                }
            }
        }
        //区
        $userDistrict = $userApply->where(['type' => 2, 'district' => json_encode($area), 'status' => 1])->first();
        if ($userDistrict) {
            //计算金额
            $areaMoney = RETAIN_TWO($money * ($Poundage['area'] * 0.01));
            //扣除平台费和复投币
            $recommendMoney = CALCULATE($Poundage, $areaMoney);
            $member = $UserModel->find_members(['uid' => $userDistrict['uid']], ['uid', 'credit1', 'credit2', 'credit3', 'credit4']);
            if ($member) {
                $member['credit2'] += $recommendMoney['money'];
                $member['credit3'] += $recommendMoney['redelivery'];
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record($ordersn, $member['uid']);
                //更新会员数据
                $userAttributes = $UserModel->where(['uid' => $member['uid']])->update($member['attributes']);
                if ($userAttributes) {
                    //添加记录
                    $this->addOrder($member['uid'], $areaMoney, 5, '区/县代理分润', $recommendMoney, $company_id, $ordersn);
                }
            }
        }
    }


    /**
     * 会员管理
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function member(Request $request)
    {
        $data = $request->all();
        $data['keyword'] = empty($data['keyword']) ? "" : $data['keyword'];
        $memberModel = new Members;
        $ShopOrderModel = new ShopOrder();
        $ShopOrderCommentModel = new ShopOrderComment();
        $UserModel = new Members();
        $RecordTransaction = new RecordTransaction();
        $SetPoundage = new Poundage();
        $userApply = new Address();
        $microMall = new MicroMall();
        $micro = $microMall->where('id', 1)->first();
        switch ($data['class']) {
            case 'select': //会员列表
                $member = $memberModel->get_member($data['keyword']);
//                $allMember = $memberModel->get_member($data['keyword'],false);
//                if ($allMember) {
//                    $credit1_total = 0;
//                    $credit2_total = 0;
//                    $credit5_total = 0;
//                    foreach ($allMember as $v){
//                        $credit1_total += $v['credit1'];
//                        $credit2_total += $v['credit2'];
//                        $credit5_total += $v['credit5'];
//                    }
//                }
                if ($member) {
                    foreach ($member as $k => $v) {
                        $referrer = $memberModel->find_members(['uid' => $v['referrer']], ['name']);
                        $nodes = $memberModel->find_members(['uid' => $v['nodes']], ['phone']);
                        $member[$k]['referrer_phone'] = $referrer['name'];
                        $money = ShopOrder::where('uid', $v['uid'])->where('status', '>', 0)->sum('originalprice');
                        $member[$k]['money'] = $money;
                        $member[$k]['nodes_phone'] = $nodes['phone'];
                        $member[$k]['direct_num'] = $memberModel->where('referrer', $v['uid'])->count();
                        $member[$k]['voucher'] = $v['voucher'] == '' ? '0.00' : $v['voucher'];
                        $v["stores_number"] = $v["stores_number"] == '0' ? '暂无绑定门店' : $v["stores_number"];
                        $member[$k]['store_name'] = StoresCenter::where(['number' => $v["stores_number"]])->value("shop_name");
                        if ($v['achievement'] >= $micro['tutor']) {
                            $member[$k]['vip'] = "svip";
                        } else {
                            $member[$k]['vip'] = "vip";
                        }
                    }
                    $voucher = $memberModel->where('platform_profit', 0)->sum('voucher');
                    $credit3 = $memberModel->where('platform_profit', 0)->sum('credit3');
                    $num = $memberModel->where('platform_profit', 0)->count();

//                    return ['code' => 1, 'data' => $member ,'credit1' => number_format($credit1_total,2) ,'credit2' => number_format($credit2_total,2),'credit5' => number_format($credit5_total,2)];
                    return ['code' => 1, 'data' => $member, 'credit1' => $voucher, 'credit2' => $credit3, 'credit5' => $num];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'add': //添加会员
                if ($data['members']) {
                    //检测手机号
                    if (!$data['members']['phone']) {
                        return ['code' => 0, 'data' => '手机号不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[34578]\d{9}$/", $data['members']['phone'])) {
                        return ['code' => 0, 'data' => '请填写正确的手机号'];
                    }
                    //检测密码
                    if (!$data['members']['password']) {
                        return ['code' => 0, 'data' => '密码不能为空'];
                    }
                    //检测密码格式
                    /* if (!preg_match("/^[\d]{6,16}$/",$data['members']['password'])) {
                         return ['code' => 0, 'data' => '请填写至少6位以上的密码'];
                     }*/
                    //检测确认密码
                    if (!$data['members']['repasswprd']) {
                        return ['code' => 0, 'data' => '确认密码不能为空'];
                    }
                    if ($data['members']['password'] != $data['members']['repasswprd']) {
                        return ['code' => 0, 'data' => '两次密码不一致'];
                    } else {
                        //密码加密
                        $passRand = RANDOM();
                        $data['members']['salting'] = $passRand;
                        $data['members']['password'] = ENCRYPTION($data['members']['password'], $passRand);
                        // $data['members']['password'] = md5($data['members']['password'].'baoli');
                    }
                    //检测分享人
                    if (!$data['members']['referrer']) {
                        return ['code' => 0, 'data' => '分享人不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[34578]\d{9}$/", $data['members']['referrer'])) {
                        return ['code' => 0, 'data' => '请填写正确的分享人手机号'];
                    }
                    //检测接点人
                    if (!$data['members']['nodes']) {
                        return ['code' => 0, 'data' => '接点人不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[34578]\d{9}$/", $data['members']['nodes'])) {
                        return ['code' => 0, 'data' => '请填写正确的接点人手机号'];
                    }
                    //检测区域
                    if (!$data['members']['area']) {
                        return ['code' => 0, 'data' => '请选择接点区域'];
                    }

                    //用户姓名
                    if (!$data['members']['user_name']) {
                        return ['code' => 0, 'data' => '请输入姓名'];
                    }
                    //检测手机号
                    $phoneInfo = $memberModel->find_member($data['members']['phone']);
                    if ($phoneInfo['phone']) {
                        return ['code' => 0, 'data' => '该手机号已存在'];
                    }
                    //设置默认账号
                    $data['members']['name'] = $data['members']['phone'];
                    //检测用户名
                    $memberName = $memberModel->where('name', $data['members']['name'])->first();
                    if ($memberName['name']) {
                        return ['code' => 0, 'data' => '用户已存在'];
                    }
                    //获取分享人数据
                    $referrerInfo = $memberModel->find_member($data['members']['referrer']);
                    if (!$referrerInfo) {
                        return ['code' => 0, 'data' => '分享人不存在'];
                    } else {
                        //设置分享人ID
                        $data['members']['referrer'] = $referrerInfo['uid'];
                        //设置分享人姓名
                        $data['members']['feferrer_name'] = $referrerInfo['user_name'];
                    }
                    //获取接点人数据
                    $nodesInfo = $memberModel->find_member($data['members']['nodes']);
                    //A-B区
                    //判断注册区域
                    $area = $memberModel->where(['nodes' => $nodesInfo['uid'], 'area' => $data['members']['area']])->first();
                    if ($area) {
                        return ['code' => 0, 'data' => $data['members']['area'] . '区域已被注册'];
                    }
                    //设置接点人ID
                    $data['members']['nodes'] = $nodesInfo['uid'];
                    $data['members']['nodes_name'] = $nodesInfo['user_name'];
                    //注册时间
                    $data['members']['enroll_time'] = time();
                    //直商城开关 1开 2关
                    $data['members']['straight_shop_isdown'] = $nodesInfo['straight_shop_isdown'];
                    //超级商城开关 1开 2关
                    $data['members']['isdown'] = $nodesInfo['isdown'];
                    //支付密码随机数
                    $data['members']['salting_pay'] = RANDOM();
                    //默认支付密码
                    $data['members']['password_pay'] = ENCRYPTION($data['members']['phone'], $data['members']['salting_pay']);
                    //设置创建时间
                    $data['members']['createtime'] = time();
                    $rico = Members::create($data['members']);
                }
                if ($rico) {
                    //改变节点人的id
                    if ($data['members']['area'] == 'A') {
                        $memberModel->where(['uid' => $nodesInfo['uid']])->update(['a' => $rico['id']]);
                    } else {
                        $memberModel->where(['uid' => $nodesInfo['uid']])->update(['b' => $rico['id']]);
                    }
                    return ['code' => 1, 'data' => '添加成功'];
                } else {
                    return ['code' => 0, 'data' => '添加失败'];
                }
                break;
            case 'addSuperUsers': //添加超级商城会员
                if ($data['members']) {
                    //检测手机号
                    if (!$data['members']['phone']) {
                        return ['code' => 0, 'data' => '手机号不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[3456789]\d{9}$/", $data['members']['phone'])) {
                        return ['code' => 0, 'data' => '请填写正确的手机号'];
                    }
                    //检测用户名
                    $memberPhone = $memberModel->where('name', $data['members']['phone'])->first();
                    if ($memberPhone) {
                        return ['code' => 0, 'data' => '手机号已被注册'];
                    }
                    //检测分享人
                    if (!$data['members']['referrer']) {
                        return ['code' => 0, 'data' => '分享人不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[3456789]\d{9}$/", $data['members']['referrer'])) {
                        return ['code' => 0, 'data' => '请填写正确的分享人手机号'];
                    }
                    //用户姓名
                    if (!$data['members']['user_name']) {
                        return ['code' => 0, 'data' => '请输入姓名'];
                    }
                    //注册等级
                    if (empty($data['members']['super_level'])) {
                        return ['code' => 0, 'data' => '会员等级不为空！'];
                    }
                    //检测手机号分享人
                    $referrerInfo = $memberModel->where('name', $data['members']['referrer'])->first();
                    if (empty($referrerInfo)) {
                        return ['code' => 0, 'data' => '分享人不存在'];
                    }
                    $memberData = array();
                    $memberData['user_name'] = $data['members']['user_name'];
                    $memberData['phone'] = $data['members']['phone'];
                    //密码加密
                    $passRand = RANDOM();
                    $memberData['salting'] = $passRand;
                    $memberData['password'] = ENCRYPTION($data['members']['phone'], $passRand);
                    //设置默认账号
                    $memberData['name'] = $data['members']['phone'];
                    //获取分享人数据
                    if ($data['members']['type'] == 1) {
                        //设置分享人ID
                        $memberData['referrer'] = $referrerInfo['uid'];
                    }
                    //设置分享人姓名
                    $memberData['feferrer_name'] = $referrerInfo['user_name'];
                    //注册时间
                    $memberData['enroll_time'] = time();
                    //直商城开关 1开 2关
                    //$memberData['straight_shop_isdown'] = $referrerInfo['straight_shop_isdown'];
                    $memberData['straight_shop_isdown'] = 2;
                    //超级商城开关 1开 2关
                    $memberData['isdown'] = $referrerInfo['isdown'];
                    //支付密码随机数
                    $memberData['salting_pay'] = RANDOM();
                    //默认支付密码
                    $memberData['password_pay'] = ENCRYPTION($data['members']['phone'], $memberData['salting_pay']);
                    //激活时间
                    $memberData['activation_time'] = time();

                    $memberData['registered'] = 1; //1 已激活 0 未激活
                    $memberData['is_withdraw'] = 1;//0 禁止提现 1 允许
                    $memberData['is_shift'] = 1;   //0 禁止转账 1 允许
                    $memberData['voucher'] = 1;   //0 默认份额 1
                    $memberData['super_level'] = $data['members']['super_level'];   //报单商城等级
                    if ($data['members']['super_level'] == 1) {
                        $memberData['super_level_name'] = 'vip';   //报单商城等级
                    } else {
                        $memberData['super_level_name'] = '导师';   //报单商城等级
                    }
                    $money = 0;
//                    $member = Members::get()->toArray();
//                    foreach ($member as $k => $v){
//                        $teamCount = Members::where('referrer',$v['uid'])->count();
//                        Members::where('uid',$v)->update(['super_recommend' => $teamCount]);
//                    }
//                    die;
                    $rico = $memberModel->insertGetId($memberData);
                    if ($rico) {
//                        //交易记录表
//                        $RecordTransaction = new RecordTransaction();
//                        $recommendData = [
//                            'uid' => $rico,
//                            'ordersn' => $ordersn,
//                            'money' => $voucher,
//                            'type' => 1,
//                            'time' => time(),
//                            'explain' => '个人消费积分份额',
//                            'remark' => '个人消费积分份额：' . $voucher ,
//                        ];
//                        $TransactionId = $RecordTransaction->add_transaction($recommendData);
//                        if (empty($TransactionId)) {
//                            \Illuminate\Support\Facades\DB::rollback();  //回滚
//                            return ['code' => 0, 'data' => '交易失败'];
//                        }
                        //业绩设置
                        $QualityModel = new SetQuality();
                        $Quality = $QualityModel->get()->toArray();
                        $puid = $rico;
                        $arrays = [];
                        $share = $referrer = $memberData['referrer'];
                        $members = $UserModel->where('uid', '<=', $rico)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();
                        foreach ($members as $k => $v) {
                            if (!empty($v['referrer'])) {
                                if ($referrer == $v['uid'] || $v['uid'] == $rico) {
                                    $referrer = $v['referrer'];
                                    $arrays[$v['uid']] = $v['referrer'];
//                                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, $points);
                                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, 0);
                                    //上级uid
                                    $puid = $v['uid'];
                                    //更新会员数据
                                    $UserModel->where(['uid' => $v['uid']])->update(
                                        [
                                            'credit1' => $v['credit1'],
                                            'credit2' => $v['credit2'],
                                            'credit3' => $v['credit3'],
                                            'credit4' => $v['credit4'],
                                            'credit5' => $v['credit5'],
                                            'level' => $v['level'],
                                            'level_name' => $v['level_name'],
                                            'level_grade' => $v['level_grade'],
                                            'super_recommend' => $v['super_recommend'],
                                            'team_member_count' => $v['team_member_count'],
                                            'super_team_count' => $v['super_team_count'],
                                            'super_small_team_count' => $v['super_small_team_count'],
                                        ]);
                                }
                            }

                        }
                        return ['code' => 1, 'data' => '添加成功'];
                    } else {
                        return ['code' => 0, 'data' => '添加失败'];
                    }
                }

                break;
            case 'editType': //禁止用户
                if ($data['uid']) {
                    //获取用户
                    $res = Members::where('uid', $data['uid'])->first();
                    $data['type'] = $res['type'] == 1 ? 0 : 1;
                    $member = Members::where('uid', $data['uid'])->update(array_only($data, ['type']));
                    if ($member) {
                        return ['code' => 1, 'data' => '设置成功'];
                    } else {
                        return ['code' => 0, 'data' => '设置失败'];
                    }
                }
                break;
            case 'package': //查出礼包信息及会员地址信息
                if ($data['uid']) {
                    //获取大礼包相关信息
                    $packAgeData = ShopGoods::where(['number' => '00006', 'type' => 1, 'status' => 2])->select('id', 'goodsname', 'memberprice', 'freight')->first();
                    //获取该用户所有地址信息
                    $memberAllAdress = Address::where(['uid' => $data['uid']])->select('id', 'name', 'phone', 'province', 'city', 'district', 'address', 'default')->get()->toArray();
                    //获取该用户币值信息及匹配是否余额不足
                    $MemberMoneyInfo = Members::where('uid', $data['uid'])->select('credit1', 'credit2', 'voucher')->first();
                    $userAllPayMoney = $packAgeData['memberprice'] + $packAgeData['freight'];
                    $userHaveMoney = $MemberMoneyInfo['credit1'] + $MemberMoneyInfo['credit2'] + $MemberMoneyInfo['voucher'];
                    if ($userHaveMoney < $packAgeData['memberprice']) {
                        $MembersPayFor = 0;//余额不足
                    } else {
                        $MembersPayFor = 1;
                    }
                    return ['code' => 1, 'data' => ['packAgeData' => $packAgeData, 'memberAllAdress' => $memberAllAdress, 'MembersPayFor' => $MembersPayFor, 'packagePayAll' => $userAllPayMoney]];
                } else {
                    return ['code' => 0, 'data' => '会员id获取失败!'];
                }
                break;
            case 'packageBuy':
                if (empty($data['goodsid'])) {
                    return ['code' => 0, 'data' => '礼包id不能为空'];
                }
                if (empty($data['uid'])) {
                    return ['code' => 0, 'data' => '会员id不能为空'];
                }
                if (empty($data['addressid'])) {
                    return ['code' => 0, 'data' => '收货地址id不能为空'];
                }
                if (empty($data['price'])) {
                    return ['code' => 0, 'data' => '礼包价格不能为空'];
                }
                if (empty($data['freight'])) {
                    return ['code' => 0, 'data' => '礼包运费不能为空'];
                }
                $user = $UserModel->where(['uid' => $data['uid']])->first();
                if ($data['is_self'] == 1) {
                    $allPayMoney = $data['price'];
                } else {
                    $allPayMoney = $data['price'] + $data['freight'];
                }
                $haveMoney = $user['credit1'] + $user['credit2'] + $user['voucher'];
                if ($haveMoney < $allPayMoney) {
                    return ['code' => 0, 'data' => '余额不足'];
                }

                $credit1PayMoney = 0;
                $credit2PayMoney = 0;
                $voucherPayMoney = 0;

                if ($user['voucher'] >= $allPayMoney) {
                    $voucherPayMoney = $allPayMoney;
                    $credit1PayMoney = 0;
                    $credit2PayMoney = 0;
                } else {
                    $voucherLastMoney = $allPayMoney - $user['voucher'];
                    $voucherPayMoney = $user['voucher'];
                    if ($user['credit1'] >= $voucherLastMoney) {
                        $credit1PayMoney = $voucherLastMoney;
                        $credit2PayMoney = 0;
                    } else {
                        $credit1PayMoney = $user['credit1'];
                        $credit2PayMoney = $voucherLastMoney - $user['credit1'];
                    }
                }

                $recommendRemark = '电子币：' . -$credit1PayMoney . '，奖励币：' . -$credit2PayMoney . '，代金券：' . -$voucherPayMoney . '，积分：0';
                $company_id = $user['company_id'];
                $addressDataAdd = Address::where(['id' => $data['addressid']])->select('name', 'phone', 'province', 'city', 'district', 'address')->first();
                $Poundage = $SetPoundage->where(['id' => 1])->first()->toArray();
                $micro = $microMall->get()->toArray();
                $ordersn = ORDER_SN();
                DB::beginTransaction();
                //创建订单
                $order = [
                    'uid' => $data['uid'],
                    'ordertype' => 2,
                    'ordersn' => $ordersn,
                    'price' => $data['price'],
                    'originalprice' => $data['price'],
                    'freight' => $data['freight'],
                    'addressid' => $data['addressid'],
                    'remark' => $data['remark'],
                    'is_self' => $data['is_self'],
                    'status' => 1,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                    'createtime' => time(),
                    'paytime' => time(),
                    'receipt_name' => $addressDataAdd['name'],
                    'receipt_adr' => $addressDataAdd['province'] . $addressDataAdd['city'] . $addressDataAdd['district'] . $addressDataAdd['address'],
                    'receipt_phone' => $addressDataAdd['phone']
                ];
                $orderID = $ShopOrderModel->add_order($order);
                if ($orderID) {
                    $this->credit2Record($ordersn, $data['uid']);
                    $thisPackGoodsname = ShopGoods::where(['number' => '00006', 'type' => 1, 'status' => 2])->value('goodsname');
                    //插入订单详情记录
                    $orderComment[] = [
                        'uid' => $data['uid'],
                        'orderid' => $orderID,
                        'goodsid' => $data['goodsid'],
                        'price' => $data['price'],
                        'goodsname' => $thisPackGoodsname,
                        'number' => 1,
                        'createtime' => time()
                    ];
                    $rico = $ShopOrderCommentModel->insert($orderComment);
                    if ($rico) {
                        //升等级
                        $complex_money = $user['complex_money'] + $data['price'];
                        $upgrade = '';
                        if ($user['tiny_level'] == 1) {
                            if ($complex_money > $micro[$user['tiny_level']]['credit3']) {
                                $user['tiny_level'] = $micro[$user['tiny_level']]['id'];
                                $user['tiny_level_name'] = $micro[$user['tiny_level']]['vip_name'];
                                $upgrade = $micro[$user['tiny_level']]['id'];
                            }
                        }
                        if ($user['tiny_level'] == 2) {
                            if ($complex_money > $micro[$user['tiny_level']]['credit3'] && $user['maker_team'] > $micro[$user['tiny_level']]['team']) {
                                $user['tiny_level'] = $micro[$user['tiny_level']]['id'];
                                $user['tiny_level_name'] = $micro[$user['tiny_level']]['vip_name'];
                                $upgrade = $micro[$user['tiny_level']]['id'];
                            }
                        }
                        if ($user['tiny_level'] == 3) {
                            if ($complex_money > $micro[$user['tiny_level']]['credit3'] && $user['maker_team'] > $micro[$user['tiny_level']]['team']) {
                                $user['tiny_level'] = $micro[$user['tiny_level']]['id'];
                                $user['tiny_level_name'] = $micro[$user['tiny_level']]['vip_name'];
                                $upgrade = $micro[$user['tiny_level']]['id'];
                            }
                        }
                        $userData = [
                            'credit1' => $user['credit1'] - $credit1PayMoney,
                            'credit2' => $user['credit2'] - $credit2PayMoney,
                            'voucher' => $user['voucher'] - $voucherPayMoney,
                            'complex_money' => $complex_money, //添加复销金额
                            'tiny_level' => $user['tiny_level'], //更改等级
                            'tiny_level_name' => $user['tiny_level_name'], //更改等级 名称
                        ];
                        $userOrder = $UserModel->where(['uid' => $data['uid']])->update($userData);
                        if (!empty($userOrder)) {
                            //添加交易记录
                            $recommendData = [
                                'uid' => $data['uid'],
                                'ordersn' => $ordersn,//关联order表订单编号
                                'money' => -$allPayMoney,
                                'type' => 1,
                                'time' => time(),
                                'explain' => '微商城',
                                'company_id' => $company_id,
                                'remark' => $recommendRemark,
                            ];
                            $TransactionId = $RecordTransaction->add_transaction($recommendData);
                            if (!empty($TransactionId)) {
                                //奖金计算
                                $bonus = $this->bonusMicro($data['uid'], $user['referrer'], $micro, $Poundage, $data['price'], $company_id, $upgrade, $ordersn);
                                if (empty($bonus)) {
                                    //查询代理区域
                                    $address = $userApply->select('province', 'city', 'district')->where(['id' => $data['addressid']])->first();
                                    $this->agency($data['price'], $company_id, $Poundage, $address['province'], $address['city'], $address['district'], $ordersn);
                                    DB::commit();
                                    return ['code' => 1, 'data' => '支付成功'];
                                } else {
                                    DB::rollback();
                                    return ['code' => 0, 'data' => '奖金计算失败,请重新购买'];
                                }
                            } else {
                                DB::rollback();
                                return ['code' => 0, 'data' => '会员交易记录添加失败'];
                            }
                        } else {
                            DB::rollback();
                            return ['code' => 0, 'data' => '会员数据更新失败'];
                        }
                    } else {
                        DB::rollback();
                        return ['code' => 0, 'data' => '创建订单详情失败!'];
                    }
                } else {
                    DB::rollback();
                    return ['code' => 0, 'data' => '创建订单失败!'];
                }
                break;
            case 'delstore':
                $data = Members::where('uid', $data['uid'])->update(['stores_number' => '0']);
                if ($data) {
                    return ['code' => 1, 'data' => '重置成功'];
                } else {
                    return ['code' => 0, 'data' => '重置失败'];
                }
                break;
            case 'setGrilled'://扒点
                if ($data['uid']) {
                    //获取用户
                    $member = Members::where('uid', $data['uid'])->update(array_only($data['Datas'], ['grilled']));
                    if ($member) {
                        Log::info(Auth::user()->name . '用户设置扒手`');
                        return ['code' => 1, 'data' => '设置成功'];
                    } else {
                        return ['code' => 0, 'data' => '设置失败'];
                    }
                }
                break;
            case 'delete': //删除用户
                $data['type'] = -1;
                $member = Members::where('uid', $data['uid'])->update(array_only($data, ['type']));
                if ($member) {
                    Log::info(Auth::user()->name . '用户删除会员`');
                    return ['code' => 1, 'data' => '删除成功'];
                } else {
                    return ['code' => 0, 'data' => '删除失败'];
                }
                break;
            case 'finds': //查询用户资料
                if ($data['uid']) {
                    //用户信息
                    $memberInfo = Members::where('uid', $data['uid'])->first();
                    $memberInfo['referrer_phone'] = Members::where('uid', $memberInfo['referrer'])->value('name');
                    $memberInfo['feferrer_name'] = Members::where('uid', $memberInfo['referrer'])->value('user_name');
                    $address = Address::where('uid', $data['uid'])->get()->toArray();
                    $memberInfo['address'] = $address;
                    //超级商城
                    $ExShop = ExceedShop::select('id', 'vip_name')->get()->toArray();
                    if ($memberInfo) {
                        return ['code' => 1, 'data' => $memberInfo, 'ExShop' => $ExShop];
                    } else {
                        return ['code' => 0, 'data' => '没有数据'];
                    }
                }
                break;
            case 'edit': //修改会员资料
                if ($data['uid']) {
                    //检测手机号格式
                    if (!preg_match("/^1[3456789]\d{9}$/", $data['memberDetail']['name'])) {
                        return ['code' => 0, 'data' => '请填写正确的手机号'];
                    }
                    if (!empty($data['memberDetail']['super_level']) && $data['memberDetail']['super_level'] == 2) {
                        //超级商城
                        $ExShop = ExceedShop::where('id', $data['memberDetail']['super_level'])->select('id', 'vip_name')->first();
                        $data['memberDetail']['super_level_name'] = $ExShop['vip_name'];
                        $data['memberDetail']['super_level'] = $ExShop['id'];


                    }
                    if (!empty($data['memberDetail']['super_level']) && $data['memberDetail']['super_level'] != 2) {
                        //超级商城
                        $ExShop = ExceedShop::where('id', $data['memberDetail']['super_level'])->select('id', 'vip_name')->first();
                        $data['memberDetail']['super_level_name'] = $ExShop['vip_name'];
                        $data['memberDetail']['super_level'] = $ExShop['id'];

                    }
//                    if($data['memberDetail']['name'] != $data['memberDetail']['name']){
                    $names = Members::where(['uid' => $data['uid']])->first();
                    if ($data['memberDetail']['name'] != $names['name']) {
                        $phones = Members::where(['name' => $data['memberDetail']['name']])->count();
                        if ($phones == 1) {
                            return ['code' => 0, 'data' => '账号已存在！'];
                        }
                    }
//                        $phones = Members::where(['phone' => $data['memberDetail']['phone']])->count();
//                        if($phones == 1){
//                            return ['code' => 0, 'data' => '电话已存在不能修改！'];
//                        }
                    $data['memberDetail']['phone'] = $data['memberDetail']['phone'];
//                    }
                    unset($data['memberDetail']['address']);
                    unset($data['memberDetail']['feferrer_name']);
                    unset($data['memberDetail']['referrer_phone']);
                    $member = Members::where('uid', $data['uid'])->update($data['memberDetail']);
                    if ($member) {
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                }
                break;
            case 'straight_shop_isdown': //修改直商城
                $Members = new Members();
                $users = $Members->where('uid', '>=', $data['uid'])->get()->toArray();
                $uid[0] = $data['uid'];
                $this->StraightShopIsdown($users, $uid, [], $data['straight_shop_isdown']);
                $rico = $Members->where(['uid' => $data['uid']])->update(['straight_shop_isdown' => $data['straight_shop_isdown']]);
                if ($rico) {
                    return ['code' => 1, 'data' => '修改成功'];
                } else {
                    return ['code' => 0, 'data' => '修改失败'];
                }
                break;
            case 'isdown': //修改超级商城
                $Members = new Members();
                $users = $Members->where('uid', '>=', $data['uid'])->get()->toArray();
                $uid[0] = $data['uid'];
                $this->isdown($users, $uid, [], $data['isdown']);
                $rico = $Members->where(['uid' => $data['uid']])->update(['isdown' => $data['isdown']]);
                if ($rico) {
                    return ['code' => 1, 'data' => '修改成功'];
                } else {
                    return ['code' => 0, 'data' => '修改失败'];
                }
                break;
            case 'resetPass': //重置密码
                if ($data['uid']) {
                    if ($data['Usertype'] == 1) {
                        $passRand = RANDOM();
                        $data['salting'] = $passRand;
                        $password = Members::where('uid', $data['uid'])->select('name')->first();
                        $data['password'] = ENCRYPTION($password['name'], $passRand);
                        $member = Members::where('uid', $data['uid'])->update(array_only($data, ['password', 'salting']));
                        if ($member) {
                            return ['code' => 1, 'data' => '重置成功'];
                        } else {
                            return ['code' => 0, 'data' => '重置失败'];
                        }
                    } elseif ($data['Usertype'] == 2) {
                        //重置支付密码
                        $passRand = RANDOM();
                        $data['salting_pay'] = $passRand;
                        $password = Members::where('uid', $data['uid'])->first();
                        $data['password_pay'] = ENCRYPTION($password['name'], $passRand);
                        $member = Members::where('uid', $data['uid'])->update(array_only($data, ['password_pay', 'salting_pay']));
                        if ($member) {
                            return ['code' => 1, 'data' => '重置成功'];
                        } else {
                            return ['code' => 0, 'data' => '重置失败'];
                        }

                    }
                } else {
                    return ['code' => 0, 'data' => '没有会员数据'];
                }
                break;
            case 'editUser': //手机端修改会员资料
                if ($data['uid']) {
                    if ($data['memberDetail']['phone']) {
                        //检测手机号格式
                        if (!preg_match("/^1[3456789]\d{9}$/", $data['memberDetail']['phone'])) {
                            return ['code' => 0, 'data' => '请填写正确的手机号'];
                        }
                        $count = Members::where('phone', $data['memberDetail']['phone'])->orWhere('name', $data['memberDetail']['phone'])->count();
                        if ($count) {
                            return ['code' => 0, 'data' => '账号已存在'];
                        }
                    }
                    $data['memberDetail']['name'] = $data['memberDetail']['phone'];
                    $memberDetail['is_shift'] = $data['memberDetail']['is_shift'];
                    $memberDetail['is_withdraw'] = $data['memberDetail']['is_withdraw'];
                    if ($data['memberDetail']['phone']) {
                        $memberDetail['phone'] = $data['memberDetail']['phone'];
                    }
                    if ($data['memberDetail']['user_name']) {
                        $memberDetail['user_name'] = $data['memberDetail']['user_name'];
                    }
                    if ($data['memberDetail']['phone']) {
                        $memberDetail['name'] = $data['memberDetail']['name'];
                    }

//                    dump($memberDetail);exit;
                    $member = Members::where('uid', $data['uid'])->update($memberDetail);
                    if ($member) {
                        return ['code' => 1, 'data' => '修改成功'];
                    } else {
                        return ['code' => 0, 'data' => '修改失败'];
                    }
                }
                break;
            case 'findsUser': //根据电话查询会员
                if ($data['phone']) {
                    //检测手机号
                    if (!$data['phone']) {
                        return ['code' => 0, 'data' => '手机号不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) {
                        return ['code' => 0, 'data' => '请填写正确的手机号'];
                    }
                    //查询用户
                    $memberInfo = $memberModel->find_members(['phone' => $data['phone']], ['uid', 'user_name', 'voucher', 'credit1', 'credit2', 'credit4', 'is_shift', 'is_withdraw', 'super_level']);
                    //微商城
                    $MicroMall = MicroMall::select('id', 'level_name')->get()->toArray();
                    //超级商城
                    $ExShop = ExceedShop::select('id', 'vip_name')->get()->toArray();
                    if ($memberInfo) {
                        return ['code' => 1, 'data' => $memberInfo, 'MicroMall' => $MicroMall, 'ExShop' => $ExShop];
                    } else {
                        return ['code' => 0, 'data' => '没有会员数据'];
                    }
                }
                break;
            case 'addRepay': //充值货币
                if ($data['uid']) {
                    DB::beginTransaction(); //开启事务
                    //查询用户
                    $memberInfo = Members::where('uid', $data['uid'])->select('name', 'user_name', 'phone', 'credit1', 'credit2', 'credit4', 'credit5', 'credit6', 'company_id', 'deduction_credit6')->first()->toArray();
                    Log::info('充值前:' . $memberInfo['user_name'] . $memberInfo['name'] . '的积分 -- ' . $memberInfo['credit1'] . ', 奖金积分 -- ' . $memberInfo['credit2'] . ',复销积分--' . $memberInfo['credit5']);
                    $newData['memberPrepay']['remark'] = $data['memberPrepay']['remark'];
//                    $newData['memberPrepay']['voucher'] = $data['memberPrepay']['voucher'];
                    $newData['memberPrepay']['credit1'] = $data['memberPrepay']['credit1'];
                    $newData['memberPrepay']['credit2'] = $data['memberPrepay']['credit2'];
                    $newData['memberPrepay']['credit4'] = $data['memberPrepay']['credit4'];
//                    $newData['memberPrepay']['credit6'] = $data['memberPrepay']['credit6'];
                    if ($data['memberPrepay']['credit1'] || $data['memberPrepay']['credit1'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit1']) || $data['memberPrepay']['credit1'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的电子币数值'];
                        }
                    }
                    if ($data['memberPrepay']['credit2'] || $data['memberPrepay']['credit2'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit2']) || $data['memberPrepay']['credit2'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的奖励币数值'];
                        }
                    }
                    if ($data['memberPrepay']['credit4'] || $data['memberPrepay']['credit4'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit4']) || $data['memberPrepay']['credit4'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的积分数值'];
                        }
                    }
//                    if($data['memberPrepay']['voucher'] || $data['memberPrepay']['voucher'] == '0'){
//                        if(!is_numeric($data['memberPrepay']['voucher']) || $data['memberPrepay']['voucher']<=0){
//                            return ['code' => 0, 'data' => '请输入正确的代金劵数值'];
//                        }
//                    }
//                    if($data['memberPrepay']['credit6'] || $data['memberPrepay']['credit6'] == '0'){
//                        if(!is_numeric($data['memberPrepay']['credit6']) || $data['memberPrepay']['credit6']<=0){
//                            return ['code' => 0, 'data' => '请输入正确的启动金数值'];
//                        }
//                    }

                    //计算结果
//                    $data['memberPrepay']['voucher'] = (float)bcadd($memberInfo['voucher'],$data['memberPrepay']['voucher'],2);
                    $data['memberPrepay']['credit1'] = (float)bcadd($memberInfo['credit1'], $data['memberPrepay']['credit1'], 2);
                    $data['memberPrepay']['credit2'] = (float)bcadd($memberInfo['credit2'], $data['memberPrepay']['credit2'], 2);
                    $data['memberPrepay']['credit4'] = (float)bcadd($memberInfo['credit4'], $data['memberPrepay']['credit4'], 2);
//                    $data['memberPrepay']['credit6'] = (float)bcadd($memberInfo['credit6'],$data['memberPrepay']['credit6'],2);
                    //5秒之内不许重复提交
                    $createdAt = transaction::where(['uid' => $data['uid'], 'type' => 4])->orderBy('id', 'desc')->select('created_at')->first();
                    if ($createdAt) {
                        if (strtotime($createdAt['created_at']) + 5 > time()) {
                            return ['code' => 0, 'data' => '点击太快了,休息一会儿'];
                        }
                    }
                    if (Members::where('uid', $data['uid'])->update([
                        'credit1' => $data['memberPrepay']['credit1'],
                        'credit2' => $data['memberPrepay']['credit2'],
                        'credit4' => $data['memberPrepay']['credit4'],
//                        'credit6'=>$data['memberPrepay']['credit6'],
//                        'voucher'=>$data['memberPrepay']['voucher'],
                    ])) {
                        //查询数据库
                        $first = Members::where('uid', $data['uid'])->select('credit1', 'credit2', 'credit4', 'credit6', 'deduction_credit6', 'company_id', 'voucher')->first();
                        //判断各种币是否相等
                        if (bcsub($first['credit1'], $data['memberPrepay']['credit1']) == '0' && bcsub($first['credit2'], $data['memberPrepay']['credit2']) == '0') {
                            //交易记录
                            $transactionNewData = [];
                            //充值记录
                            $transactionNewDetail = [];
                            //积分

                            if ($newData['memberPrepay']['credit1']) {
                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit1'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = '积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //备注
                                $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                                //类型
                                $transactionDetail['type'] = 1;
                                //价格
                                $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->user_name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit1'] . '积分`');
                            }

//                            var_dump($newData['memberPrepay']['credit2']);exit;
                            //奖励积分
                            if ($newData['memberPrepay']['credit2']) {

                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit2'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = '奖励积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //备注
                                $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                                //类型
                                $transactionDetail['type'] = 2;
                                //价格
                                $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->user_name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit2'] . '奖励积分`');


                            }
//                            阅读积分
                            if ($newData['memberPrepay']['credit4']) {
                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit4'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = 'e+积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;
                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //类型
                                $transactionDetail['type'] = 4;
                                //价格
                                $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit4'] . '积分`');
                            }
//                            启动金
//                            if ($newData['memberPrepay']['credit6']) {
//                                //用户ID
//                                $transactionData['uid'] = $data['uid'];
//                                //订单编号
//                                $transactionData['ordersn'] = ORDER_SN();
//                                //充值金额
//                                $transactionData['money'] = $newData['memberPrepay']['credit6'];
//                                //充值类型
//                                $transactionData['type'] = 6;
//                                //添加时间
//                                $transactionData['time'] = time();
//                                //充值类型
//                                $transactionData['explain'] = '启动金充值 : '.$newData['memberPrepay']['remark'];
//
//                                $transactionData['remark'] = $newData['memberPrepay']['remark'];
//
//                                $transactionNewData[] = $transactionData;
//                                //充值记录 start
//                                $transactionDetail['money'] = $newData['memberPrepay']['credit6'];
//                                //用户id
//                                $transactionDetail['uid'] = $data['uid'];
//                                //类型
//                                $transactionDetail['type'] = 6;
//                                //价格
//                                $transactionDetail['money'] = $newData['memberPrepay']['credit6'];
//                                //操作人
//                                $transactionDetail['operator'] = Auth::user()->name;
//                                //创建时间
//                                $transactionDetail['createtime'] = time();
//                                //操作IP
//                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
//                                $transactionNewDetail[] = $transactionDetail;
//                                Log::info(Auth::user()->name.'给'.$memberInfo['name'].'充值'.$newData['memberPrepay']['credit6'].'启动金`');
//                            }
//                            代金劵
//                            if ($newData['memberPrepay']['voucher']) {
//                                //用户ID
//                                $transactionData['uid'] = $data['uid'];
//                                //订单编号
//                                $transactionData['ordersn'] = ORDER_SN();
//                                //充值金额
//                                $transactionData['money'] = $newData['memberPrepay']['voucher'];
//                                //充值类型
//                                $transactionData['type'] = 4;
//                                //添加时间
//                                $transactionData['time'] = time();
//                                //充值类型
//                                $transactionData['explain'] = '代金劵充值 : '.$newData['memberPrepay']['remark'];
//
//                                $transactionData['remark'] = $newData['memberPrepay']['remark'];
//
//                                $transactionNewData[] = $transactionData;
//
//                                //充值记录 start
//                                $transactionDetail['money'] = $newData['memberPrepay']['voucher'];
//                                //用户id
//                                $transactionDetail['uid'] = $data['uid'];
//                                //类型
//                                $transactionDetail['type'] = 5;
//                                //价格
//                                $transactionDetail['money'] = $newData['memberPrepay']['voucher'];
//                                //操作人
//                                $transactionDetail['operator'] = Auth::user()->name;
//                                //创建时间
//                                $transactionDetail['createtime'] = time();
//                                //操作IP
//                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
//                                $transactionNewDetail[] = $transactionDetail;
//                                Log::info(Auth::user()->name.'给'.$memberInfo['name'].'充值'.$newData['memberPrepay']['voucher'].'代金劵');
//                            }
                            //循环插入交易记录
                            foreach ($transactionNewData as $k => $v) {
                                $rows = transaction::create($v);
                                if ($rows) {
                                    $transactionNewDetail[$k]['tid'] = $rows['id'];
                                } else {
                                    DB::rollback();  //回滚
                                    return ['code' => 0, 'data' => '增加失败'];
                                }
                            }

                            //循环插入充值记录
                            foreach ($transactionNewDetail as $key => $value) {
                                $RecordDataCreate = RecordrRecharge::create($value);
                                if (!$RecordDataCreate) {
                                    DB::rollback();  //回滚
                                    return ['code' => 0, 'data' => '增加失败'];
                                }
                            }
                            DB::commit();  //提交
                            Log::info('充值后:' . $memberInfo['user_name'] . $memberInfo['name'] . '的积分 -- ' . $first['credit1'] . ', 奖励积分 -- ');
                            return ['code' => 1, 'data' => '增加成功'];
                        } else {
                            $cred1 = empty($newData['memberPrepay']['credit1']) ? "" : $newData['memberPrepay']['credit1'] . ' 积分` ';
                            $cred1 .= empty($newData['memberPrepay']['credit2']) ? "" : $newData['memberPrepay']['credit2'] . ' 奖励积分` ';
                            $cred1 .= empty($newData['memberPrepay']['credit4']) ? "" : $newData['memberPrepay']['credit4'] . ' e+积分` ';
//                            $cred1 .= empty($newData['memberPrepay']['voucher']) ? "" : $newData['memberPrepay']['voucher'] . ' 代金劵` ';
//                            $cred1 .= empty($newData['memberPrepay']['credit6']) ? "" : $newData['memberPrepay']['credit6'] . ' 启动金` ';
                            Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 充值 ' . $cred1 . '----- 失败');
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '增加失败'];
                        }
                    } else {
                        $cred1 = empty($newData['memberPrepay']['credit1']) ? "" : $newData['memberPrepay']['credit1'] . ' 积分` ';
                        $cred1 .= empty($newData['memberPrepay']['credit2']) ? "" : $newData['memberPrepay']['credit2'] . ' 奖励积分` ';
                        $cred1 .= empty($newData['memberPrepay']['credit4']) ? "" : $newData['memberPrepay']['credit4'] . ' e+积分` ';
//                        $cred1 .= empty($newData['memberPrepay']['voucher']) ? "" : $newData['memberPrepay']['voucher'] . ' 代金劵` ';
//                        $cred1 .= empty($newData['memberPrepay']['credit6']) ? "" : $newData['memberPrepay']['credit6'] . ' 启动金` ';
                        Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 充值 ' . $cred1 . '----- 失败');
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '充值失败,请重新充值'];
                    }
                }
                break;
            case 'minusRepay': //减少货币
                if ($data['uid']) {
//                    var_dump($data);exit;
                    DB::beginTransaction(); //开启事务
                    $memberInfo = Members::where('uid', $data['uid'])->first();
                    $newData['memberPrepay']['credit1'] = $data['memberPrepay']['credit1'];
                    $newData['memberPrepay']['credit2'] = $data['memberPrepay']['credit2'];
                    $newData['memberPrepay']['credit4'] = $data['memberPrepay']['credit4'];
//                    $newData['memberPrepay']['voucher'] = $data['memberPrepay']['voucher'];
//                    $newData['memberPrepay']['credit6'] = $data['memberPrepay']['credit6'];
                    $newData['memberPrepay']['remark'] = $data['memberPrepay']['remark'];

                    if ($data['memberPrepay']['credit1']) {
                        if (!is_numeric($data['memberPrepay']['credit1']) || $data['memberPrepay']['credit1'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的电子币数值'];
                        }
                    } elseif ($data['memberPrepay']['credit2']) {
                        if (!is_numeric($data['memberPrepay']['credit2']) || $data['memberPrepay']['credit2'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的奖励币数值'];
                        }
                    } elseif ($data['memberPrepay']['credit4']) {
                        if (!is_numeric($data['memberPrepay']['credit4']) || $data['memberPrepay']['credit4'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的积分数值'];
                        }
                    }
//                    elseif ($data['memberPrepay']['voucher']){
//                        if(!is_numeric($data['memberPrepay']['voucher']) || $data['memberPrepay']['voucher']<=0){
//                            return ['code' => 0, 'data' => '请输入正确的代金劵数值'];
//                        }
//                    }elseif ($data['memberPrepay']['credit6']){
//                        if(!is_numeric($data['memberPrepay']['credit6']) || $data['memberPrepay']['credit6']<=0){
//                            return ['code' => 0, 'data' => '请输入正确的启动金数值'];
//                        }
//                        if ($memberInfo['credit6'] < $data['memberPrepay']['credit6']){
//                            return ['code' => 0, 'data' => '启动金不足'];
//                        }
//                    }
//                    $data['memberPrepay']['voucher'] = $memberInfo['voucher'] - $data['memberPrepay']['voucher'];
                    $data['memberPrepay']['credit1'] = $memberInfo['credit1'] - $data['memberPrepay']['credit1'];
                    $data['memberPrepay']['credit2'] = $memberInfo['credit2'] - $data['memberPrepay']['credit2'];
                    $data['memberPrepay']['credit4'] = $memberInfo['credit4'] - $data['memberPrepay']['credit4'];
//                    $data['memberPrepay']['credit6'] = $memberInfo['credit6'] - $data['memberPrepay']['credit6'];

                    //5秒秒之内不许重复提交
                    $createdAt = transaction::where(['uid' => $data['uid']])->orderBy('id', 'desc')->select('created_at')->first();
                    if ($createdAt) {
                        if (strtotime($createdAt['created_at']) + 5 > time()) {
                            return ['code' => 0, 'data' => '点击太快了,休息一会儿'];
                        }
                    }
                    $member = Members::where('uid', $data['uid'])->update(array_only($data['memberPrepay'], ['credit1', 'credit2', 'credit4', 'credit6', 'deduction_credit6']));
                    if (empty($member) || !$member) {
                        DB::rollback();  //回滚
                        Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 扣除货币失败 ');
                        return ['code' => 0, 'data' => '扣除失败'];
                    }
                    //查询数据库
                    $first = Members::where('uid', $data['uid'])->select('credit1', 'credit2', 'credit4', 'credit6')->first();


                    if (bcsub($first['credit1'], $data['memberPrepay']['credit1']) == '0' && bcsub($first['credit2'], $data['memberPrepay']['credit2']) == '0') {
                        //交易记录
                        $transactionNewData = [];
                        //充值记录
                        $transactionNewDetail = [];
                        //代金劵
//                        if ($newData['memberPrepay']['voucher']) {
//                            //用户ID
//                            $transactionData['uid'] = $data['uid'];
//                            //订单编号
//                            $transactionData['ordersn'] = ORDER_SN();
//                            //充值金额
//                            $transactionData['money'] = '-'.$newData['memberPrepay']['voucher'];
//                            //充值类型
//                            $transactionData['type'] = 4;
//                            //添加时间
//                            $transactionData['time'] = time();
//                            //充值类型
//                            $transactionData['explain'] = '扣除代金劵 : '.$newData['memberPrepay']['remark'];
//
//                            $transactionData['remark'] = $newData['memberPrepay']['remark'];
//
//                            $transactionNewData[] = $transactionData;
//
//                            //充值记录 start
//                            $transactionDetail['money'] = $newData['memberPrepay']['voucher'];
//                            //用户id
//                            $transactionDetail['uid'] = $data['uid'];
//                            //类型
//                            $transactionDetail['type'] = 5;
//                            //价格
//                            $transactionDetail['money'] = $newData['memberPrepay']['voucher'];
//                            //操作人
//                            $transactionDetail['operator'] = Auth::user()->name;
//                            //创建时间
//                            $transactionDetail['createtime'] = time();
//                            //操作IP
//                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
//                            $transactionNewDetail[] = $transactionDetail;
//                            Log::info(Auth::user()->name.'给'.$memberInfo['name'].'扣除'.$newData['memberPrepay']['voucher'].'代金劵`');
//                        }
                        //积分
                        if ($newData['memberPrepay']['credit1']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit1'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
//                            $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //备注
                            $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                            //类型
                            $transactionDetail['type'] = 1;
                            //价格
                            $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->user_name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit1'] . '积分`');
                        }
                        //奖励积分
                        if ($newData['memberPrepay']['credit2']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit2'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除奖励积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //备注
                            $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                            //类型
                            $transactionDetail['type'] = 2;
                            //价格
//                            $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->user_name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit2'] . '奖励积分`');
                        }
                        if ($newData['memberPrepay']['credit4']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit4'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //类型
                            $transactionDetail['type'] = 4;
                            //价格
                            $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit4'] . '积分`');
                        }
                        //循环插入交易记录
                        foreach ($transactionNewData as $k => $v) {
                            $rows = transaction::create($v);
                            if ($rows) {
                                $transactionNewDetail[$k]['tid'] = $rows['id'];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '扣除货币失败'];
                            }
                        }

                        //循环插入充值记录
                        foreach ($transactionNewDetail as $key => $value) {
                            $RecordDataCreate = RecordrRecharge::create($value);
                            if (!$RecordDataCreate) {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '扣除货币失败'];
                            }
                        }
                        DB::commit();  //提交
                        return ['code' => 1, 'data' => '扣除货币成功'];
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '扣除货币失败'];
                    }
                }
                break;
            case 'teamFind':
                //判断用户名
                $data['name'] = $data['name'] ? $data['name'] : 13899998888;
                //查询当前用户
                $memberInfo = Members::where('name', $data['name'])->select('uid', 'name', 'user_name', 'level_name', 'a', 'b')->first();

                // print_r($memberInfo);
                if ($memberInfo) {
                    $memData['id'] = $memberInfo['uid'];
                    $memData['name'] = $memberInfo['name'];
                    $memData['title'] = $memberInfo['user_name'];
                    // $memData = Members::where('uid',$memberInfo['a'])->get()->toArray();

                    // print_r($memData);exit;
                    return ['code' => 1, 'data' => $memData];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;

        }
    }

    /**
     * 会员充值
     * @param Request $request
     * @return array
     */
    public function memberRecharge(Request $request)
    {
        $data = $request->all();
        $memberModel = new Members();
        switch ($data['class']) {
            case 'findsUser': //根据电话查询会员
                if ($data['phone']) {
                    //检测手机号
                    if (!$data['phone']) {
                        return ['code' => 0, 'data' => '手机号不能为空'];
                    }
                    //检测手机号格式
                    if (!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) {
                        return ['code' => 0, 'data' => '请填写正确的手机号'];
                    }
                    //查询用户
                    $memberInfo = $memberModel->find_members(['name' => $data['phone']], ['uid', 'name', 'user_name', 'voucher', 'credit1', 'credit2', 'credit4', 'credit5', 'is_shift', 'is_withdraw', 'super_level']);
                    //微商城
                    $MicroMall = MicroMall::select('id', 'level_name')->get()->toArray();
                    //超级商城
                    $ExShop = ExceedShop::select('id', 'vip_name')->get()->toArray();
                    if ($memberInfo) {
                        return ['code' => 1, 'data' => $memberInfo, 'MicroMall' => $MicroMall, 'ExShop' => $ExShop];
                    } else {
                        return ['code' => 0, 'data' => '没有会员数据'];
                    }
                }
                break;
            case 'addRepay': //充值货币
                if ($data['uid']) {
                    DB::beginTransaction(); //开启事务
                    //查询用户
                    $memberInfo = Members::where('uid', $data['uid'])->select('name', 'user_name', 'phone', 'credit1', 'credit2', 'credit4', 'credit5', 'credit6', 'company_id', 'deduction_credit6', 'voucher')->first()->toArray();
                    Log::info('充值前:' . $memberInfo['user_name'] . $memberInfo['name'] . '的积分 -- ' . $memberInfo['credit1'] . ', 奖金积分 -- ' . $memberInfo['credit2']);
                    $newData['memberPrepay']['remark'] = $data['memberPrepay']['remark'];
                    $newData['memberPrepay']['credit1'] = $data['memberPrepay']['credit1'];
                    $newData['memberPrepay']['credit2'] = $data['memberPrepay']['credit2'];
                    $newData['memberPrepay']['credit4'] = $data['memberPrepay']['credit4'];
                    $newData['memberPrepay']['credit5'] = $data['memberPrepay']['credit5'];
                    if ($data['memberPrepay']['credit1'] || $data['memberPrepay']['credit1'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit1']) || $data['memberPrepay']['credit1'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    }
                    if ($data['memberPrepay']['credit2'] || $data['memberPrepay']['credit2'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit2']) || $data['memberPrepay']['credit2'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    }
                    if ($data['memberPrepay']['credit4'] || $data['memberPrepay']['credit4'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit4']) || $data['memberPrepay']['credit4'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    }
                    if ($data['memberPrepay']['credit5'] || $data['memberPrepay']['credit5'] == '0') {
                        if (!is_numeric($data['memberPrepay']['credit5']) || $data['memberPrepay']['credit5'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    }
                    //计算结果
                    $data['memberPrepay']['credit1'] = (float)bcadd($memberInfo['credit1'], $data['memberPrepay']['credit1'], 2);
                    $data['memberPrepay']['credit2'] = (float)bcadd($memberInfo['credit2'], $data['memberPrepay']['credit2'], 2);
                    $data['memberPrepay']['credit4'] = (float)bcadd($memberInfo['credit4'], $data['memberPrepay']['credit4'], 2);
                    $data['memberPrepay']['credit5'] = (float)bcadd($memberInfo['credit5'], $data['memberPrepay']['credit5'], 2);
                    //5秒之内不许重复提交
                    $createdAt = transaction::where(['uid' => $data['uid'], 'type' => 4])->orderBy('id', 'desc')->select('created_at')->first();
                    if ($createdAt) {
                        if (strtotime($createdAt['created_at']) + 5 > time()) {
                            return ['code' => 0, 'data' => '点击太快了,休息一会儿'];
                        }
                    }
                    if (Members::where('uid', $data['uid'])->update([
                        'credit1' => $data['memberPrepay']['credit1'],
                        'credit2' => $data['memberPrepay']['credit2'],
                        'credit4' => $data['memberPrepay']['credit4'],
                        'credit5' => $data['memberPrepay']['credit5'],
                    ])) {
                        //查询数据库
                        $first = Members::where('uid', $data['uid'])->select('credit1', 'credit2', 'credit4', 'credit5', 'credit6', 'deduction_credit6', 'company_id', 'voucher')->first();
                        //判断各种币是否相等
                        if (bcsub($first['credit1'], $data['memberPrepay']['credit1']) == '0' && bcsub($first['credit2'], $data['memberPrepay']['credit2']) == '0' && bcsub($first['credit4'], $data['memberPrepay']['credit4']) == '0' && bcsub($first['credit5'], $data['memberPrepay']['credit5']) == '0') {
                            //交易记录
                            $transactionNewData = [];
                            //充值记录
                            $transactionNewDetail = [];
                            //电子积分
                            if ($newData['memberPrepay']['credit1']) {
                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit1'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = '购物积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //备注
                                $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                                //类型
                                $transactionDetail['type'] = 1;
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
//                                var_dump($transactionNewDetail);exit;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit1'] . '积分`');
                            }
                            //奖励积分
                            if ($newData['memberPrepay']['credit2']) {

                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit2'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = '奖金积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //备注
                                $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                                //类型
                                $transactionDetail['type'] = 2;
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit2'] . '奖励积分`');


                            }
                            //e+积分
                            if ($newData['memberPrepay']['credit4']) {

                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit4'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = 'e+积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //类型
                                $transactionDetail['type'] = 4;
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit4'] . 'e+积分`');


                            }
                            //复销积分
                            if ($newData['memberPrepay']['credit5']) {

                                //用户ID
                                $transactionData['uid'] = $data['uid'];
                                //订单编号
                                $transactionData['ordersn'] = ORDER_SN();
                                //充值金额
                                $transactionData['money'] = $newData['memberPrepay']['credit5'];
                                //充值类型
                                $transactionData['type'] = 4;
                                //添加时间
                                $transactionData['time'] = time();
                                //充值类型
                                $transactionData['explain'] = '复销积分充值 : ' . $newData['memberPrepay']['remark'];

                                $transactionData['remark'] = $newData['memberPrepay']['remark'];

                                $transactionNewData[] = $transactionData;

                                //充值记录 start
                                $transactionDetail['money'] = $newData['memberPrepay']['credit5'];
                                //用户id
                                $transactionDetail['uid'] = $data['uid'];
                                //备注
                                $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                                //类型
                                $transactionDetail['type'] = 5;
                                //操作人
                                $transactionDetail['operator'] = Auth::user()->name;
                                //创建时间
                                $transactionDetail['createtime'] = time();
                                //操作IP
                                $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                                $transactionNewDetail[] = $transactionDetail;
                                Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '充值' . $newData['memberPrepay']['credit5'] . '复销积分`');


                            }
                            //循环插入交易记录
                            foreach ($transactionNewData as $k => $v) {
                                $rows = transaction::create($v);
                                if ($rows) {
                                    $transactionNewDetail[$k]['tid'] = $rows['id'];
                                } else {
                                    DB::rollback();  //回滚
                                    return ['code' => 0, 'data' => '增加失败'];
                                }
                            }

                            //循环插入充值记录
                            foreach ($transactionNewDetail as $key => $value) {
                                $RecordDataCreate = RecordrRecharge::create($value);
                                if (!$RecordDataCreate) {
                                    DB::rollback();  //回滚
                                    return ['code' => 0, 'data' => '增加失败'];
                                }
                            }
                            DB::commit();  //提交
                            Log::info('充值后:' . $memberInfo['user_name'] . $memberInfo['name'] . '的积分 -- ' . $first['credit1'] . ', 积分 -- ');
                            return ['code' => 1, 'data' => '增加成功'];
                        } else {
                            $cred1 = empty($newData['memberPrepay']['credit1']) ? "" : $newData['memberPrepay']['credit1'] . ' 购物积分` ';
                            $cred1 .= empty($newData['memberPrepay']['credit2']) ? "" : $newData['memberPrepay']['credit2'] . ' 奖金积分` ';
                            $cred1 .= empty($newData['memberPrepay']['credit4']) ? "" : $newData['memberPrepay']['credit4'] . ' e+积分` ';
                            $cred1 .= empty($newData['memberPrepay']['credit5']) ? "" : $newData['memberPrepay']['credit5'] . ' 复销积分` ';
                            Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 充值 ' . $cred1 . '----- 失败');
                            DB::rollback();  //回滚
                            return ['code' => 0, 'data' => '增加失败'];
                        }
                    } else {
                        $cred1 = empty($newData['memberPrepay']['credit1']) ? "" : $newData['memberPrepay']['credit1'] . ' 购物积分` ';
                        $cred1 .= empty($newData['memberPrepay']['credit2']) ? "" : $newData['memberPrepay']['credit2'] . ' 奖金积分` ';
                        $cred1 .= empty($newData['memberPrepay']['credit4']) ? "" : $newData['memberPrepay']['credit4'] . ' e+积分` ';
                        $cred1 .= empty($newData['memberPrepay']['credit5']) ? "" : $newData['memberPrepay']['credit5'] . ' 复销积分` ';
                        Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 充值 ' . $cred1 . '----- 失败');
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '充值失败,请重新充值'];
                    }
                }
                break;
            case 'minusRepay': //减少货币
                if ($data['uid']) {
                    DB::beginTransaction(); //开启事务
                    $memberInfo = Members::where('uid', $data['uid'])->first();
                    $newData['memberPrepay']['credit1'] = $data['memberPrepay']['credit1'];
                    $newData['memberPrepay']['credit2'] = $data['memberPrepay']['credit2'];
                    $newData['memberPrepay']['credit4'] = $data['memberPrepay']['credit4'];
                    $newData['memberPrepay']['credit5'] = $data['memberPrepay']['credit5'];
                    $newData['memberPrepay']['remark'] = $data['memberPrepay']['remark'];

                    if ($data['memberPrepay']['credit1']) {
                        if (!is_numeric($data['memberPrepay']['credit1']) || $data['memberPrepay']['credit1'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    } elseif ($data['memberPrepay']['credit2']) {
                        if (!is_numeric($data['memberPrepay']['credit2']) || $data['memberPrepay']['credit2'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的数值'];
                        }
                    } elseif ($data['memberPrepay']['credit4']) {
                        if (!is_numeric($data['memberPrepay']['credit4']) || $data['memberPrepay']['credit4'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的积分数值'];
                        }
                    } elseif ($data['memberPrepay']['credit5']) {
                        if (!is_numeric($data['memberPrepay']['credit5']) || $data['memberPrepay']['credit5'] <= 0) {
                            return ['code' => 0, 'data' => '请输入正确的积分数值'];
                        }
                    }
                    $data['memberPrepay']['credit1'] = $memberInfo['credit1'] - $data['memberPrepay']['credit1'];
                    $data['memberPrepay']['credit2'] = $memberInfo['credit2'] - $data['memberPrepay']['credit2'];
                    $data['memberPrepay']['credit4'] = $memberInfo['credit4'] - $data['memberPrepay']['credit4'];
                    $data['memberPrepay']['credit5'] = $memberInfo['credit5'] - $data['memberPrepay']['credit5'];

                    //5秒秒之内不许重复提交
                    $createdAt = transaction::where(['uid' => $data['uid']])->orderBy('id', 'desc')->select('created_at')->first();
                    if ($createdAt) {
                        if (strtotime($createdAt['created_at']) + 5 > time()) {
                            return ['code' => 0, 'data' => '点击太快了,休息一会儿'];
                        }
                    }
                    $member = Members::where('uid', $data['uid'])->update(array_only($data['memberPrepay'], ['credit1', 'credit2', 'credit4', 'credit5', 'credit6', 'deduction_credit6']));
                    if (empty($member) || !$member) {
                        DB::rollback();  //回滚
                        Log::info(Auth::user()->name . ' 给 ' . $memberInfo['phone'] . ' 扣除货币失败 ');
                        return ['code' => 0, 'data' => '扣除失败'];
                    }
                    //查询数据库
                    $first = Members::where('uid', $data['uid'])->select('credit1', 'credit2', 'credit4', 'credit5', 'credit6')->first();


                    if (bcsub($first['credit1'], $data['memberPrepay']['credit1']) == '0' && bcsub($first['credit2'], $data['memberPrepay']['credit2']) == '0' && bcsub($first['credit4'], $data['memberPrepay']['credit4']) == '0' && bcsub($first['credit5'], $data['memberPrepay']['credit5']) == '0') {
                        //交易记录
                        $transactionNewData = [];
                        //充值记录
                        $transactionNewDetail = [];
                        if ($newData['memberPrepay']['credit1']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit1'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除购物积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit1'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //备注
                            $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                            //类型
                            $transactionDetail['type'] = 1;
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit1'] . '积分`');
                        }
                        //奖励积分
                        if ($newData['memberPrepay']['credit2']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit2'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除奖金积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit2'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //备注
                            $transactionDetail['credit'] = $newData['memberPrepay']['remark'];
                            //类型
                            $transactionDetail['type'] = 2;
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit2'] . '奖励积分`');
                        }
                        if ($newData['memberPrepay']['credit4']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit4'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除兑换e+积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit4'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //类型
                            $transactionDetail['type'] = 4;
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit4'] . 'e+积分`');
                        }
                        //复销币扣除
                        if ($newData['memberPrepay']['credit5']) {
                            //用户ID
                            $transactionData['uid'] = $data['uid'];
                            //订单编号
                            $transactionData['ordersn'] = ORDER_SN();
                            //充值金额
                            $transactionData['money'] = '-' . $newData['memberPrepay']['credit5'];
                            //充值类型
                            $transactionData['type'] = 4;
                            //添加时间
                            $transactionData['time'] = time();
                            //充值类型
                            $transactionData['explain'] = '扣除复销积分 : ' . $newData['memberPrepay']['remark'];

                            $transactionData['remark'] = $newData['memberPrepay']['remark'];

                            $transactionNewData[] = $transactionData;

                            //充值记录 start
                            $transactionDetail['money'] = $newData['memberPrepay']['credit5'];
                            //用户id
                            $transactionDetail['uid'] = $data['uid'];
                            //类型
                            $transactionDetail['type'] = 5;
                            //操作人
                            $transactionDetail['operator'] = Auth::user()->name;
                            //创建时间
                            $transactionDetail['createtime'] = time();
                            //操作IP
                            $transactionDetail['ip'] = $_SERVER["REMOTE_ADDR"];
                            $transactionNewDetail[] = $transactionDetail;
                            Log::info(Auth::user()->name . '给' . $memberInfo['name'] . '扣除' . $newData['memberPrepay']['credit4'] . '复销积分`');
                        }
                        //循环插入交易记录
                        foreach ($transactionNewData as $k => $v) {
                            $rows = transaction::create($v);
                            if ($rows) {
                                $transactionNewDetail[$k]['tid'] = $rows['id'];
                            } else {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '扣除货币失败'];
                            }
                        }

                        //循环插入充值记录
                        foreach ($transactionNewDetail as $key => $value) {
                            $RecordDataCreate = RecordrRecharge::create($value);
                            if (!$RecordDataCreate) {
                                DB::rollback();  //回滚
                                return ['code' => 0, 'data' => '扣除货币失败'];
                            }
                        }
                        DB::commit();  //提交
                        return ['code' => 1, 'data' => '扣除货币成功'];
                    } else {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '扣除货币失败'];
                    }
                }
                break;
        }
    }

    /**
     * 修改直商城开关
     * @param array $data
     * @param array $uid
     * @param array $pid
     * @param int $type
     */
    public function StraightShopIsdown($data = array(), $uid = array(), $pid = array(), $type = 2)
    {
        $pid = $pid;
        $nodesid = [];
        foreach ($data as $k => $v) {
            foreach ($uid as $key => $value) {
                if ($v['referrer'] == $value) {
                    $pid[] = $v['uid'];
                    $nodesid[] = $v['uid'];
                }
            }
        }
        if (!empty($nodesid)) {
            $this->StraightShopIsdown($data, $nodesid, $pid, $type);
        } else {
            $Members = new Members();
            foreach ($pid as $k => $v) {
                $Members->where(['uid' => $v])->update(['straight_shop_isdown' => $type]);
            }
        }
    }

    /**
     * 修改超级商城开关
     * @param array $data
     * @param array $uid
     * @param array $pid
     * @param int $isdown
     */
    public function isdown($data = array(), $uid = array(), $pid = array(), $isdown = 2)
    {
        $pid = $pid;
        $nodesid = [];
        foreach ($data as $k => $v) {
            foreach ($uid as $key => $value) {
                if ($v['nodes'] == $value) {
                    $pid[] = $v['uid'];
                    $nodesid[] = $v['uid'];
                }
            }
        }
        if (!empty($nodesid)) {
            $this->isdown($data, $nodesid, $pid, $isdown);
        } else {
            $Members = new Members();
            foreach ($pid as $k => $v) {
                $Members->where(['uid' => $v])->update(['isdown' => $isdown]);
            }
        }
    }

    /**
     * 团队谱首页
     */
    public function team(Request $request)
    {
        $name = $request->get('name');
        if (empty($name)) {
            $name = '13899998888';
        }
        $MembersModel = new Members();
        //查询当前用户
        $memberInfo = $MembersModel->find_members(['name' => $name], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], ['phone' => $name]);
        //	$data = array();
        if ($memberInfo) {
            $data = $this->subordinate($memberInfo['uid']);
        }
        $memberInfo['children'] = $data;
        $memberInfo['name'] = $name;
//        $registered = ($memberInfo['registered'] == 1)?"已激活":"未激活";
//        $memberInfo['name'] = [
//            'name' => $name,
//            'title' => '<a href="/admin/members/team?name='.$memberInfo['nodes'].'">'.$memberInfo['user_name']."<br/>".$memberInfo['level_name'].'<br/>'.$memberInfo['area'].$registered.'<br/>'.$memberInfo['original_money'].'<br/>',
//        ];
        //判断格式
        if (!$memberInfo) {
            return ['code' => 0, 'data' => '无效号码'];
        }
        return view('Admin.team', ['data' => $memberInfo]);

    }

    //第一层
    public function subordinate($uid = null)
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        foreach ($memberInfo as $k => $v) {
            $className = '';
            if ($v['area'] == 'A') {
                $className = 'middle-level';
            }
            $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
            $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
            $data[] = [
                'name' => $v['phone'],
                'title' => '<a href="/admin/members/team?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . $registered . '<br/>' . $v['original_money'] . '<br/>' . $time . '</a>',
                'className' => $className,
//                'area' => $v['area'], //区域
//                'level_name' => $v['level_name'], //等级名字
//                'time' => empty($v['enroll_time'])?:date('Y-m-d',$v['enroll_time']), //注册时间
//                'registered' => ($v['registered'] == 1)?'已激活':'未激活',
                'children' => $this->subordinate2($v['uid'])
            ];
        }
        return json_encode($data);


    }

    //第二层
    public function subordinate2($uid = null, $data = array())
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
//        dump($memberInfo);exit;
        foreach ($memberInfo as $k => $v) {
            $className = '';
            if ($v['area'] == 'A') {
                $className = 'middle-level';
            }
            $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
            $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
            $data[] = [
                'name' => $v['phone'],
                'title' => '<a href="/admin/members/team?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . $registered . '<br/>' . $v['original_money'] . '<br/>' . $time . '</a>',
                'className' => $className,
                'area' => $v['area'], //区域
//                'level_name' => $v['level_name'], //等级名字
//                'time' => empty($v['enroll_time'])?:date('Y-m-d',$v['enroll_time']), //注册时间
//                'registered' => ($v['registered'] == 1)?'已激活':'未激活',
                'children' => $this->subordinate3($v['uid'])
            ];
        }
        return $data;
    }

    //第三层
    public function subordinate3($uid = null, $data = array())
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered', 'original_money'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        foreach ($memberInfo as $k => $v) {
            $className = '';
            if ($v['area'] == 'A') {
                $className = 'middle-level';
            }
            $registered = ($v['registered'] == 1) ? "已激活" : "未激活";
            $time = empty($v['enroll_time']) ?: date('Y-m-d', $v['enroll_time']);
            $data[] = [
                'name' => $v['phone'],
                'title' => '<a href="/admin/members/team?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . $registered . '<br/>' . $v['original_money'] . '<br/>' . $time . '</a>',
                'className' => $className,
//                'area' => $v['area'], //区域
//                'level_name' => $v['level_name'], //等级名字
//                'time' => empty($v['enroll_time'])?:date('Y-m-d',$v['enroll_time']), //注册时间
//                'registered' => ($v['registered'] == 1)?'已激活':'未激活',
//                'children' => $this->subordinate4($v['uid']),
            ];
        }
        return $data;
    }

    //第四层
    public function subordinate4($uid = null, $data = array())
    {
        $MembersModel = new Members();
        $memberInfo = $MembersModel->get_members(['nodes' => $uid], ['uid', 'phone', 'name', 'user_name', 'level_name', 'nodes', 'area', 'enroll_time', 'registered'], null, 'area', 'asc');
        if (empty($memberInfo)) {
            return false;
        }
        foreach ($memberInfo as $k => $v) {
            $className = '';
            if ($v['area'] == 'A') {
                $className = 'middle-level';
            }
            $data[] = [
                'name' => $v['phone'],
                'title' => '<a href="/admin/members/team?name=' . $v['phone'] . '">' . $v['user_name'] . "<br/>" . $v['level_name'] . '<br/>' . $v['area'] . '</a>',
                'className' => $className,
//                'area' => $v['area'], //区域
//                'level_name' => $v['level_name'], //等级名字
//                'time' => empty($v['enroll_time'])?:date('Y-m-d',$v['enroll_time']), //注册时间
//                'registered' => ($v['registered'] == 1)?'已激活':'未激活',
            ];
        }
        return $data;
    }

    /*
     * 代理商
     */
    public function doApply(Request $request)
    {
        $data = $request->all();
        $Poundage = Poundage::get()->first();
        switch ($data['class']) {
            //代理商列表
            case 'select':
                //关键字
                $keyword = empty($data['keyword']) ? 0 : $data['keyword'];
                $applyData = Apply::select();
                //类型
                if (isset($keyword['type'])) {
                    $applyData = $applyData->where('type', $keyword['type']);
                }

                //状态
                if (isset($keyword['status'])) {
                    $applyData = $applyData->where('status', $keyword['status']);
                }
                //关键字
                if (!empty($keyword['keyword'])) {
                    $applyData = $applyData->where('name', 'like', '%' . $keyword['keyword'] . '%')->orWhere('phone', 'like', '%' . $keyword['keyword'] . '%');
                }
                //分页
                $applyData = $applyData->orderBy('id', 'desc')->paginate(15);
                foreach ($applyData as $k => $y) {
                    $y['district'] = json_decode($y['district'], true);
//                    $y['allMoney'] = Transaction::where('uid' , $y['uid'])->where('explain','like','%'.'代理分润')->sum('money');
//                    $bonusRecord = Transaction::where('uid' , $y['uid'])->where('explain','like','%'.'代理分润')->select('money')->get()->toArray();
//                    $price = 0;
//                    foreach ( $bonusRecord as $key => $value ){
//                        $recommendMoney = CALCULATE($Poundage,$value['money']);
//                        $price += $recommendMoney['money'];
//                    }
//                    $y['bonus'] = (string)$price;
                }
                if ($applyData) {
                    return ['code' => 1, 'data' => $applyData];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            //审核
            case 'edit':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $res = Apply::where('id', $data['id'])->first();
                    if ($res['status'] == 0) {
                        $data['status'] = 1;
                    } elseif ($res['status'] == 1) {
                        $data['status'] = 3;
                    }
                    $data['verifier'] = $adminUser->name;
                    $apply = Apply::where('id', $data['id'])->update(array_only($data, ['status', 'verifier']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '设置成功'];
                    } else {
                        return ['code' => 0, 'data' => '设置失败'];
                    }
                }
                break;
            //拒绝
            case 'reEdit':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $res = Apply::where('id', $data['id'])->first();
                    $data['status'] = 2;
                    $data['verifier'] = $adminUser->user_name;
                    $apply = Apply::where('id', $data['id'])->update(array_only($data, ['status', 'verifier']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '拒绝成功'];
                    } else {
                        return ['code' => 0, 'data' => '拒绝失败'];
                    }
                }
                break;
            //开通
            case 'back':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $res = Apply::where('id', $data['id'])->first();
                    $data['status'] = 0;
                    $data['verifier'] = $adminUser->user_name;
                    $apply = Apply::where('id', $data['id'])->update(array_only($data, ['status', 'verifier']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '开通成功'];
                    } else {
                        return ['code' => 0, 'data' => '开通失败'];
                    }
                }
                break;
            case 'delete': //删除
                break;
            //代理申请
            case 'apply':
                if ($data['address']) {
                    $MembersModel = new Members();
                    $user = $MembersModel->where(['name' => $data['address']['phone']])->select('uid', 'name', 'user_name', 'phone')->first();
                    if (empty($user)) {
                        return ['code' => 0, 'data' => '没有会员数据'];
                    }
                    //市代理
                    if (empty($data['address']['id'])) {
                        if ($data['address']['type'] == 1) {
                            $cityData = Apply::where(['province' => $data['address']['province'], 'city' => $data['address']['city'], 'status' => 1])->get()->toArray();
                            if (!empty($cityData)) {
                                foreach ($cityData as $k => $v) {
                                    $districts = explode(',', $data['address']['districts']);
//                                    var_dump($districts);
                                    foreach ($districts as $key => $value) {
                                        $array = explode($value, json_decode($v['district']));
                                        if (count($array) > 1) {
                                            return ['code' => 0, 'data' => $value . '已被其他市代理添加'];
                                        }
                                    }
                                }
                            }
                        } else {//区县代
                            $district = Apply::where(['city' => $data['address']['city'], 'district' => json_encode($data['address']['districts']), 'status' => 1])->first();
                            if ($district) {
                                return ['code' => 0, 'data' => $data['address']['district'] . '已有区县代'];
                            }
                        }
                    }
                    $data['address']['uid'] = $user['uid'];
                    $data['address']['user'] = $user['name'];
                    $data['address']['name'] = $user['user_name'];
                    $data['address']['phone'] = $user['phone'];
                    $data['address']['district'] = json_encode($data['address']['districts']);
                    unset($data['address']['districts']);
                    if ($data['address']['id']) {
                        $data['address']['status'] = 1;
                        $userRoic = Apply::where('id', $data['address']['id'])->update($data['address']);
                    } else {
                        $data['address']['status'] = 0;
                        $userRoic = Apply::create($data['address']);
                    }
                    if ($userRoic) {
                        return ['code' => 1, 'data' => '申请成功,等带审核'];
                    } else {
                        return ['code' => 0, 'data' => '申请失败'];
                    }
                }
                break;
        }
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 代理分公司合伙人列表
     */

    public function agentList()
    {
        return view('Admin/partner');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 代理分公司合伙人列表
     */
    public function partnerList(Request $request)
    {
        $data = $request->all();
        switch ($data['class']) {
            //代理合伙人列表
            case 'select':
                //关键字
                $keyword = empty($data['keyword']) ? 0 : $data['keyword'];
                $applyModel = new SetRebate();
                $applyData = $applyModel->where(['a_id' => $data['id']])
                    ->where('status', '!=', -1)
                    ->where(function ($query) use ($keyword) {
                        if (!empty($keyword['type'])) {
                            $query->where($keyword['type'], 1);
                        }
                        if (!empty($keyword['keyword'])) {
                            $query->where(function ($query) use ($keyword) {
                                $query->where('user_name', 'like', '%' . $keyword['keyword'] . '%')
                                    ->orWhere('name', 'like', '%' . $keyword['keyword'] . '%');
                            });
                        }
                    })
                    ->orderBy('id', 'desc')->paginate(15);


                //分页
//                $applyData = $applyData->paginate(15);
                if ($applyData) {
                    return ['code' => 1, 'data' => $applyData];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            //代理合伙人是否存在系统
            case 'find_member': //删除
                if ($data['name']) {
                    $members = Members::where('name', $data['name'])->select('name', 'user_name')->first();
                    if ($members) {
                        return ['code' => 1, 'data' => $members];
                    } else {
                        return ['code' => 0, 'data' => '此系统暂无该会员'];
                    }
                }
                break;
            //代理合伙人申请
            case 'add':
                if ($data['id']) {
                    if (empty($data['name'])) {
                        return ['code' => 0, 'data' => '账号不能为空'];
                    }
                    if (empty($data['user_name'])) {
                        return ['code' => 0, 'data' => '姓名不能为空'];
                    }
                    $name = Members::where('name', $data['name'])->first();
                    if (!$name) {
                        return ['code' => 0, 'data' => '此会员不存在'];
                    }
                    $members = SetRebate::where(['name' => $data['name'], 'a_id' => $data['id'], 'is_partner' => $data['is_partner'], 'status' => 1])->select('is_partner')->first();
                    if ($members) {
                        return ['code' => 0, 'data' => '此会员身份已存在'];
                    }
                    $members = SetRebate::where(['name' => $data['name'], 'a_id' => $data['id'], 'is_service' => $data['is_service'], 'status' => 1])->select('is_service')->first();
                    if ($members) {
                        return ['code' => 0, 'data' => '此会员身份已存在'];
                    }
                    $members = SetRebate::where(['name' => $data['name'], 'a_id' => $data['id'], 'is_ceo' => $data['is_ceo'], 'status' => 1])->select('is_ceo')->first();
                    if ($members) {
                        return ['code' => 0, 'data' => '此会员身份已存在'];
                    }
                    $members = SetRebate::where(['name' => $data['name'], 'a_id' => $data['id'], 'is_investor' => $data['is_investor'], 'status' => 1])->select('is_investor')->first();
                    if ($members) {
                        return ['code' => 0, 'data' => '此会员身份已存在'];
                    }
                    $adminUser = Auth::user();
                    $data['information']['verifier'] = $adminUser->user_name;
                    $data['information']['a_id'] = $data['id'];
                    $data['information']['is_partner'] = $data['is_partner'];
                    $data['information']['is_service'] = $data['is_service'];
                    $data['information']['is_ceo'] = $data['is_ceo'];
                    $data['information']['is_investor'] = $data['is_investor'];
                    $data['information']['status'] = 1;
                    $data['information']['name'] = $data['name'];
                    $data['information']['user_name'] = $data['user_name'];
                    $maxSort = SetRebate::where(['a_id' => $data['id']])->max('sort');
                    $data['information']['sort'] = empty($maxSort) ? 1 : ($maxSort + 1);
                    $userRoic = SetRebate::create($data['information']);
                    if ($userRoic) {
                        return ['code' => 1, 'data' => '添加成功'];
                    } else {
                        return ['code' => 0, 'data' => '添加失败'];
                    }
                }
                break;
            //代理查找
            case 'find':
                if ($data['id']) {
                    $members = SetRebate::where('id', $data['id'])->select('name', 'user_name', 'is_partner', 'is_service', 'is_ceo', 'is_investor')->first();
                    if ($members) {
                        return ['code' => 1, 'data' => $members];
                    } else {
                        return ['code' => 0, 'data' => '暂无此会员信息'];
                    }
                }
                break;
            //代理合伙人编辑
            case 'edit':
                if ($data['id']) {
                    if (empty($data['name'])) {
                        return ['code' => 0, 'data' => '账号不能为空'];
                    }
                    if (empty($data['user_name'])) {
                        return ['code' => 0, 'data' => '姓名不能为空'];
                    }
                    $adminUser = Auth::user();
                    $data['information']['verifier'] = $adminUser->user_name;
                    $data['information']['is_partner'] = $data['is_partner'];
                    $data['information']['is_service'] = $data['is_service'];
                    $data['information']['is_ceo'] = $data['is_ceo'];
                    $data['information']['is_investor'] = $data['is_investor'];
                    $data['information']['name'] = $data['name'];
                    $data['information']['user_name'] = $data['user_name'];
                    $apply = SetRebate::where('id', $data['id'])->update(array_only($data, ['verifier', 'is_partner', 'is_service', 'is_ceo', 'is_investor', 'name', 'user_name']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '编辑成功'];
                    } else {
                        return ['code' => 0, 'data' => '编辑失败'];
                    }
                }
                break;
            //删除代理下合伙人
            case 'delete':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $data['verifier'] = $adminUser->user_name;
                    $data['status'] = -1;
                    $apply = SetRebate::where('id', $data['id'])->update(array_only($data, ['status', 'verifier']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                }


        }
    }

    /*
     * 股东管理页面
     */
    public function shareholder()
    {
        return view('Admin/shareholder');
    }

    /*
     * 股东管理
     */
    public function doShareholders(Request $request)
    {
        $data = $request->all();
        $Poundage = Poundage::get()->first();
        switch ($data['class']) {
            case 'select':
                //关键字
                $keyword = empty($data['keyword']) ? 0 : $data['keyword'];
                $shareholders = Members::select('uid', 'name', 'user_name', 'DT_shareholder', 'shareholder', 'DT_performance', 'performance', 'equity_price', 'equity_price2');

                $shareholders = $shareholders->where(function ($sql) {
                    return $sql->where('DT_shareholder', 1)
                        ->orWhere('shareholder', 1);
                });
                //类型
                if (!empty($keyword['type'])) {
                    if ($keyword['type'] == 1) {//DT股东
                        $shareholders = $shareholders->where('DT_shareholder', 1);
                    }
                    if ($keyword['type'] == 2) {//典华股东
                        $shareholders = $shareholders->where('shareholder', 1);
                    }
                }
                //关键字
                if (!empty($keyword['keyword'])) {
                    $shareholders = $shareholders->where(function ($sql) use ($keyword) {
                        $sql->where('user_name', 'like', '%' . $keyword['keyword'] . '%')
                            ->orWhere('phone', 'like', '%' . $keyword['keyword'] . '%');
                    });
                }
                //分页
                $shareholders = $shareholders->paginate(15);

                foreach ($shareholders as $key => $value) {
                    if (is_null($value['DT_performance'])) {
                        $shareholders[$key]['DT_performance'] = 0;
                    }
                    if (is_null($value['performance'])) {
                        $shareholders[$key]['performance'] = 0;
                    }
                    if (is_null($value['equity_price'])) {
                        $shareholders[$key]['equity_price'] = 0;
                    }
                    if (is_null($value['equity_price2'])) {
                        $shareholders[$key]['equity_price2'] = 0;
                    }
                    //DT内衣实际分红
                    $Record = Transaction::where('uid', $value['uid'])->where('explain', 'like', '%' . 'DT内衣股东分红')->get()->toArray();
                    if ($Record) {
                        $price = 0;
                        foreach ($Record as $k => $v) {
                            $recommendMoney = CALCULATE($Poundage, $v['money']);
                            $price += $recommendMoney['money'];
                        }
                        $value['real_price'] = (string)$price;
                    } else {
                        $value['real_price'] = (string)0;
                    }

                    //典华股东实际分红
                    $DTRecord = Transaction::where('uid', $value['uid'])->where('explain', '股东分红')->get()->toArray();
                    if ($DTRecord) {
                        $price = 0;
                        foreach ($DTRecord as $k => $v) {
                            $recommendMoney = CALCULATE($Poundage, $v['money']);
                            $price += $recommendMoney['money'];

                        }
                        $value['real_price2'] = (string)$price;
                    } else {
                        $value['real_price2'] = (string)0;
                    }
                    $value['DT_performance'] = (string)$value['DT_performance'];
                    $value['performance'] = (string)$value['performance'];

                }
                if ($shareholders) {
                    return ['code' => 1, 'data' => $shareholders];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            case 'add'://添加股东
                if (empty($data['shareholder']['name'])) {
                    return ['code' => 0, 'data' => '请填写会员账号'];
                }
                $member = Members::where('name', $data['shareholder']['name'])->first();
                if (!$member) {
                    return ['code' => 0, 'data' => '账号不存在'];
                }
                if (!isset($data['shareholder']['DT_shareholder']) && !isset($data['shareholder']['shareholder'])) {
                    return ['code' => 0, 'data' => '请选择开通股东类型'];
                }
                if (isset($data['shareholder']['DT_shareholder'])) {
                    if (empty($data['shareholder']['equity_price']) || $data['shareholder']['equity_price'] <= 0) {
                        return ['code' => 0, 'data' => '请输入正确的DT入股金额'];
                    }
                    if ($data['shareholder']['DT_shareholder'] == $member['DT_shareholder']) {
                        return ['code' => 0, 'data' => '已开通股东,请勿重复添加'];
                    }
                }
                if (isset($data['shareholder']['shareholder'])) {
                    if (empty($data['shareholder']['equity_price2']) || $data['shareholder']['equity_price2'] <= 0) {
                        return ['code' => 0, 'data' => '请输入正确的入股金额'];
                    }
                    if ($data['shareholder']['shareholder'] == $member['shareholder']) {
                        return ['code' => 0, 'data' => '已开通股东,请勿重复添加'];
                    }
                }
                $rico = Members::where('name', $data['shareholder']['name'])->update($data['shareholder']);
                if ($rico) {
                    return ['code' => 1, 'data' => '开通成功'];
                } else {
                    return ['code' => 0, 'data' => '开通失败'];
                }
                break;
            case 'edit'://编辑
                if ($data['shareholder']['DT_shareholder'] == 1) {
                    if (empty($data['shareholder']['equity_price']) || $data['shareholder']['equity_price'] <= 0) {
                        return ['code' => 0, 'data' => '请输入正确的DT入股金额'];
                    }
                } else {
                    $data['shareholder']['equity_price'] = 0;
                }
                if ($data['shareholder']['shareholder'] == 1) {
                    if (empty($data['shareholder']['equity_price2']) || $data['shareholder']['equity_price2'] <= 0) {
                        return ['code' => 0, 'data' => '请输入正确的入股金额'];
                    }
                } else {
                    $data['shareholder']['equity_price2'] = 0;
                }
                $rico = Members::where('name', $data['shareholder']['name'])->update($data['shareholder']);
                if ($rico) {
                    return ['code' => 1, 'data' => '修改成功'];
                } else {
                    return ['code' => 0, 'data' => '修改失败'];
                }
                break;
            case 'findmember':
                $name = Members::where('name', $data['name'])->pluck('user_name')->first();
                if ($name) {
                    return ['code' => 1, 'data' => $name];
                } else {
                    return ['code' => 0, 'data' => '用户不存在'];
                }
                break;
        }

    }

    /**
     * 导出数据
     */
    public function exportUser(Request $request)
    {
        //实例
        $memberModel = new Members;
        //接收关键字
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword']) ? "" : $info['keyword'];
        $newData[] = ['原ID', '账号', '姓名', '手机号', '等级', '分享人', '团队业绩', '荣誉级别', '电子积分', '奖金积分', '购物积分', '贡献值', '团队份额', '分红状态', '注册地址', '注册时间'];
        $data = $memberModel->get_member($info['keyword'], false);
        foreach ($data as $v) {
            $referrer = $memberModel->find_members(['uid' => $v['referrer']], ['phone']);
            $v['referrer_phone'] = $referrer['phone'];
            $address = Address::where(['uid' => $v['uid'], 'default' => 1])->first();
            $v['address'] = $address['province'] . $address['city'] . $address['district'] . $address['address'];
            $v['activation_time'] = date('Y-m-d H:i:s');
            $v['registered'] = $v['registered'] == 1 ? '已激活' : '未激活';
            if ($v['platform_profit'] == 1) {
                $v['platform_profit'] = '开启';
            } else {
                $v['platform_profit'] = '关闭';
            }
            if ($v['super_team_count'] >= 2000) {
                $v['super_level_name'] = 'SVIP';
            } else {
                $v['super_level_name'] = 'VIP';
            }
            $newData[] = [
                $v['name'],
                $v['user_name'],
                $v['phone'],
                $v['super_level_name'],
                $v['referrer_phone'],
                $v['super_team_count'],
                $v['level_name'],
                $v['credit1'],
                $v['credit2'],
                $v['credit5'],
//                $v['credit4'],
                $v['voucher'],
                $v['credit3'],
                $v['platform_profit'],
                $v['address'],
                $v['enroll_time'],

            ];
        }
        Excel::create("手猫商城会员", function ($excel) use ($newData) {
            $excel->sheet('score', function ($sheet) use ($newData) {
                $sheet->rows($newData);
            });
        })->export('xls');
    }

    /**
     * 导出会员份额数据
     */
    public function exportShare(Request $request)
    {
        //实例
        $memberModel = new Members;
        //接收关键字
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword']) ? "" : $info['keyword'];
        $newData[] = ['用户手机号', '用户昵称', '份额', '消费金额'];
        $data = $memberModel->get_member($info['keyword'], false);
        foreach ($data as $v) {
            $money = ShopOrder::where('uid', $v['uid'])->where('status', '>', 0)->sum('originalprice');
            $v['money'] = $money;
            $newData[] = [
                $v['name'],
                $v['user_name'],
                $v['voucher'],
                $v['money'],

            ];
        }
        Excel::create("手猫份额", function ($excel) use ($newData) {
            $excel->sheet('score', function ($sheet) use ($newData) {
                $sheet->rows($newData);
            });
        })->export('xls');
    }

    /**
     * 修改错误订单
     */
    public function alter()
    {
        return view('Admin.alter');
    }

    /**
     * 修改错误订单
     */
    public function alters(Request $request)
    {
        $data = $request->get('user');
        if (empty($data['order'])) {
            return ['code' => 0, 'data' => '订单不能为空'];
        }
        if (empty($data['phone'])) {
            return ['code' => 0, 'data' => '电话不能为空'];
        }
        //会员表
        $UserModel = new Members();
        //交易记录表
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $order_sn = $data['order'];
        $upgrade = $data['phone'];
        $upgradeUser = $UserModel->where(['phone' => $upgrade])->select('uid', 'user_name', 'credit2')->first()->toArray();
        if (empty($upgradeUser)) {
            return ['code' => 0, 'data' => '没有会员信息'];
        }
        $Record = $RecordTransaction->where(['ordersn' => $order_sn])->orderBy('id')->get()->toArray();
        if (empty($Record)) {
            return ['code' => 0, 'data' => '没有订单信息'];
        }
        $status = 0;
        $userId = $upgradeUser['uid'];
        $users = '';
        $money = 50;
        DB::beginTransaction(); //开启事务
        $UserModel->where(['uid' => $upgradeUser['uid']])->update(['credit2' => ($upgradeUser['credit2'] + 41)]);
        foreach ($Record as $k => $v) {
            if (substr($v['explain'], 0, 2) == 'V2') {
                $member = $UserModel->where(['uid' => $v['uid']])->first();
                $money = RETAIN_TWO(($v['money'] - ($v['money'] * 0.18)) / 2);
                $memberId = $UserModel->where(['uid' => $member['uid']])->update(['credit2' => RETAIN_TWO($member['credit2'] - $money)]);
                if (empty($memberId)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '修改失败1'];
                }
                $rico = $RecordBonus->where(['tid' => $v['id']])->update(['uid' => $userId]);
                if (empty($rico)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '修改失败2'];
                }
                $users = $v['uid'];
                $rico = $RecordTransaction->where(['id' => $v['id']])->update(['uid' => $userId]);
                if (empty($rico)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '修改失败3'];
                }
                $userId = $users;
            }
        }
        $RetreatModel = new Retreat();
        $RetreatData = [
            'ordersn' => $order_sn,
        ];
        $rico = $RetreatModel->create($RetreatData);
        if (empty($rico)) {
            DB::rollback();  //回滚
            return ['code' => 0, 'data' => '修改失败1'];
        } else {
            DB::commit();  //提交
            return ['code' => 1, 'data' => '修改成功'];
        }
        exit;
    }

    /**
     * @param Request $request
     * @return array
     * 会员升单处理
     */
    public function buyMask(Request $request)
    {
        $data = $request->all();
        $membersModel = new Members();
        $ShopOrderCommentModel = new ShopOrderComment();
        switch ($data['class']) {
            case 'getGoods': //获取限时购所有商品
                $table = ShopGoodsClassify::where(['type' => 2])->select('id');
                $classify = $table->get()->toArray();
                $pid = [];
                if (!empty($classify)) {
                    foreach ($classify as $value) {
                        $pid[] = $value['id'];
                    }
                } else {
                    return ['code' => 0, 'data' => '暂时还没有商品'];
                }
                $goods = ShopGoods::where(['type' => 1, 'status' => 2])->whereIn('cid', $pid)->select('id', 'goodsname', 'rulingprice', 'weight')->get()->toArray();
                if ($goods) {
                    return ['code' => 1, 'data' => $goods];
                } else {
                    return ['code' => 0, 'data' => '暂无商品'];
                }
                break;
            case 'address'://获取地址
                $address = Address::where('uid', $data['uid'])->get()->toArray();
                if ($address) {
                    return ['code' => 1, 'data' => $address];
                } else {
                    return ['code' => 0, 'data' => '暂无收货地址！'];
                }
                break;
            case 'pay'://支付订单
                //系统设置
                $PoundageModel = new Poundage();
                $Poundage = $PoundageModel->find_poundage();
                //超级商城设置
                $ExceedShopModel = new ExceedShop();
                $ExceedShop = $ExceedShopModel->get()->toArray();
                //业绩设置
                $QualityModel = new SetQuality();
                $Quality = $QualityModel->get()->toArray();
                //微商城设置
                $microMall = new MicroMall();
                $micro = $microMall->get()->toArray();
                $SetPoundage = new Poundage();
                $microMall = new MicroMall();
                $UserModel = new Members();
                $userApply = new Address();
                $StoresProfitRecordModel = new StoresProfitRecord();
                $RecordTransaction = new RecordTransaction();
                if (!$data['data']['id']) {
                    return ['code' => 0, 'data' => '请选择购买的商品'];
                }
                $address = Address::where('id', $data['addressId'])->first();
                $goods = ShopGoods::where('id', $data['data']['id'])->first();

                $goodsTotal = $data['data']['rulingprice'];
                $priceTotal = $goodsTotal;
                $order_type = 2;
                $referrer = $UserModel->where('uid', $data['uid'])->value('referrer');
                $users = $UserModel->where('uid', $data['uid'])->first();
                $ordersn = ORDER_SN();
                $order = [
                    'uid' => $data['uid'],
                    'num' => 1,
                    'ordertype' => $order_type, //1 直商城 2 微商城 3 0元商城 4 限时购
                    'ordersn' => $ordersn,
                    'price' => $priceTotal,
                    'is_self' => $data['is_self'],
                    'freight' => 0, //运费
                    'status' => 0,//-1取消状态，0代付款，1为已付款，2为已发货，3为成功
                    'createtime' => time(),
                    'remark' => $data['remark'],
                    'addressid' => $address['id'],
                    'receipt_name' => $address['name'],
                    'receipt_adr' => $address['province'] . $address['city'] . $address['district'] . $address['address'],
                    'receipt_phone' => $address['phone'],
                    'reward_money' => $goodsTotal,
                ];
                //生成订单
                DB::beginTransaction();
                $orders = ShopOrder::create($order);
                $orderId = $orders['id'];
                if (!$orders) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '创建订单失败'];
                }
                //生成订单详情
                $orderComment = [
                    'uid' => $data['uid'],
                    'orderid' => $orderId,
                    'goodsid' => $goods['id'],
                    'price' => $data['data']['rulingprice'],
                    'goodsname' => $goods['goodsname'],
                    'number' => $data['number'],
                    'createtime' => time(),
                ];
                $rico = $ShopOrderCommentModel->insert($orderComment);
                if (!$rico) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '创建订单失败'];
                }
                //支付订单
                $order = ShopOrder::where('id', $orderId)->first();
                //记录订单之前各会员的奖励币余额记录
                $this->credit2Record($order['ordersn'], $data['uid']);
                $order->status = 1;//修改为已支付状态
                $order->paytime = time();//修改支付时间
                $res = $order->save();
                if (!$res) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '修改订单失败'];
                }
                //生成交易记录
                $transaction = [
                    'uid' => $data['uid'],
                    'ordersn' => $order['ordersn'],
                    'money' => -$order['price'],
                    'type' => 1,
                    'time' => time(),
                    'explain' => '会员原点升单',
                    'remark' => '线下收款'
                ];
                RecordTransaction::create($transaction);
//                if ($goods['level'] == 1) {
//                    //生成交易记录
//                    $transaction = [
//                        'uid' => $data['uid'],
//                        'ordersn' => $order['ordersn'],
//                        'money' => -$order['price'],
//                        'type' => 1,
//                        'time' => time(),
//                        'explain' => '会员原点升单',
//                        'remark' => '线下收款'
//                    ];
//                    RecordTransaction::create($transaction);
//                } else {
//                    //生成交易记录
//                    $transaction = [
//                        'uid' => $data['uid'],
//                        'ordersn' => $order['ordersn'],
//                        'money' => -$order['price'],
//                        'type' => 1,
//                        'time' => time(),
//                        'explain' => '会员升平台合伙人',
//                        'remark' => '线下收款'
//                    ];
//                    RecordTransaction::create($transaction);
//                }

//                if ($goods['level'] == 1) {
                //个人消费份额
//                    $voucher = RETAIN_TWO($order['price'] / $order['price']);
                $userData = [
                    'voucher' => $users['voucher'] + 1,
                    'achievement' => $users['achievement'] + $order['price'],
                    'credit3' => $users['credit3'] + $order['price'] * 2,
                ];
                $res = $UserModel->where('uid', $data['uid'])->update($userData);
                if (empty($res)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '数据错误'];
                } else {
                    $RecordTransaction = new RecordTransaction();
                    $recommendData = [
                        'uid' => $data['uid'],
                        'ordersn' => $ordersn,
                        'money' => 1,
                        'type' => 1,
                        'time' => time(),
                        'explain' => '个人消费积分份额',
                        'remark' => '个人消费积分份额：' . 1,
                    ];
                    $TransactionId = $RecordTransaction->add_transaction($recommendData);
                    if (empty($TransactionId)) {
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '交易失败'];
                    }
                }
                //直推消费加权积分
                $referrer_voucher = RETAIN_TWO($Poundage['share'] * 1 / 100);
                if (!$referrer_voucher) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '数据错误'];
                }
//                    else{
                $member = $UserModel->where('uid', $referrer)->first();
                $shareData = [  //推荐人奖励添加 DATA
                    'voucher' => $member['voucher'] + $referrer_voucher,
                ];
                $shareUser = $UserModel->where(['uid' => $referrer])->update($shareData);
//                        var_dump($shareUser);
                if (!$shareUser) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '交易失败11'];
                }
                //交易记录表
                $RecordTransaction = new RecordTransaction();
                $recommendData = [
                    'uid' => $member['uid'],
                    'ordersn' => $ordersn,
                    'money' => $referrer_voucher,
                    'type' => 1,
                    'time' => time(),
                    'explain' => '消费推荐积分',
                    'remark' => '消费推荐积分：' . $referrer_voucher,
                ];
                $TransactionId = $RecordTransaction->add_transaction($recommendData);
                if (empty($TransactionId)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '交易失败22'];
                }
//                    }
//                }

                //加权业绩设置
                $bonusModel = new SetBonus();
                $setBonus = $bonusModel->get()->toArray();
                $super = $this->superShop($data['uid'], $referrer, $Quality, $goods['level'], $Poundage, $order['price'], $order['ordersn'], $goods['pk_integral'], $setBonus);
                if (empty($super)) {
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '奖金计算失败'];
                }
                //总公司合伙人分红
                if (!empty($order['price'] > 0)) {
                    $money = $order['price'];
                    $applyModel = new SetrebateCompany();
                    $partners = $applyModel->where(['is_one' => 1, 'status' => 1])->get()->toArray();//一级核心人员
                    $service = $applyModel->where(['is_two' => 1, 'status' => 1])->get()->toArray();
                    $ceo = $applyModel->where(['is_three' => 1, 'status' => 1])->get()->toArray();
                    $ser_count = count($service);
                    $count = count($partners);
                    $ceo_count = count($ceo);
                    if ($count == 0) {
                        $Poundage['distribution'] = 0;
                    }
                    if ($ser_count == 0) {
                        $Poundage['platform_profit'] = 0;
                    }
                    if ($ceo_count == 0) {
                        $Poundage['ceo'] = 0;
                    }
                    //总公司一级合伙人分红
                    if ($Poundage['is_one'] > 0) {
                        if ($count > 0) {
                            foreach ($partners as $k => $v) {
                                $partner = Members::where('name', $v['name'])->first();
                                $money2 = RETAIN_TWO($money * $Poundage['is_one'] / 100 / $count);
                                $recommendMoney = CALCULATE($Poundage, $money2, 2);
                                //添加记录
                                if ($partner['type'] == 1) {
                                    $partner['credit2'] += $recommendMoney['money'];
                                    $partner['credit5'] += $recommendMoney['redelivery'];
                                    //记录订单之前各会员的奖励币余额记录
                                    $res = $UserModel->where('uid', $partner['uid'])->update(['credit2' => $partner['credit2'], 'credit5' => $partner['credit5']]);
                                    $this->credit2Record($order['ordersn'], $partner['uid']);
                                    //重新赋值
                                    $addData3['money'] = $money2;
                                    $addData3['type'] = 5;
                                    $addData3['text'] = '总公司一级合伙人分润';
                                    $addData3['recommendMoney'] = $recommendMoney;
                                    $addData3['ordersn'] = $order['ordersn'];
                                    if ($res) {
                                        $this->addOrder($partner['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
                                    }
                                }
                            }
                        }
                    }

                    //总公司二级合伙人分红
                    if ($Poundage['is_two'] > 0) {
                        if ($ser_count > 0) {
                            foreach ($service as $k => $v) {
                                $ser = Members::where('name', $v['name'])->first();
                                $money3 = RETAIN_TWO($money * $Poundage['is_two'] / 100 / $ser_count);
                                $recommendMoney = CALCULATE($Poundage, $money3, 2);
                                //添加记录
                                if ($ser['type'] == 1) {
                                    $ser['credit2'] += $recommendMoney['money'];
                                    $ser['credit5'] += $recommendMoney['redelivery'];
                                    //记录订单之前各会员的奖励币余额记录
                                    $res = $UserModel->where('uid', $ser['uid'])->update(['credit2' => $ser['credit2'], 'credit5' => $ser['credit5']]);
                                    $this->credit2Record($order['ordersn'], $ser['uid']);
                                    //重新赋值
                                    $addData4['money'] = $money3;
                                    $addData4['type'] = 5;
                                    $addData4['text'] = '总公司二级合伙人分润';
                                    $addData4['recommendMoney'] = $recommendMoney;
                                    $addData4['ordersn'] = $order['ordersn'];
                                    if ($res) {
                                        $this->addOrder($ser['uid'], $addData4['money'], 5, $addData4['text'], $addData4['recommendMoney'], 0, $addData4['ordersn']);
                                    }
                                }
                            }
                        }
                    }
                    //总公司三级合伙人分红
                    if ($Poundage['is_three'] > 0) {
                        if ($ceo_count > 0) {
                            foreach ($ceo as $k => $v) {
                                $user = Members::where('name', $v['name'])->first();
                                $money4 = RETAIN_TWO($money * $Poundage['is_three'] / 100 / $ceo_count);
                                $recommendMoney = CALCULATE($Poundage, $money4, 2);
                                //添加记录
                                if ($user['type'] == 1) {
                                    $user['credit2'] += $recommendMoney['money'];
                                    $user['credit5'] += $recommendMoney['redelivery'];
                                    //记录订单之前各会员的奖励币余额记录
                                    $res = $UserModel->where('uid', $user['uid'])->update(['credit2' => $user['credit2'], 'credit5' => $user['credit5']]);
                                    $this->credit2Record($order['ordersn'], $user['uid']);
                                    //重新赋值
                                    $addData5['money'] = $money4;
                                    $addData5['type'] = 5;
                                    $addData5['text'] = '总公司三级合伙人分润';
                                    $addData5['recommendMoney'] = $recommendMoney;
                                    $addData5['ordersn'] = $order['ordersn'];
                                    if ($res) {
                                        $this->addOrder($user['uid'], $addData5['money'], 5, $addData5['text'], $addData5['recommendMoney'], 0, $addData5['ordersn']);
                                    }
                                }
                            }
                        }
                    }


                }
//                //消费份额实时分红
//                if ($Poundage['set_order_consumption'] > 0) {
//                    //消费总份额
//                    $member = $UserModel->where('voucher', '>', '0')->where('platform_profit', 1)->sum('voucher');
//                    //单份份额
//                    $integral = RETAIN_TWO(($order['price'] * $Poundage['set_order_consumption'] / 100) / $member);
////                $num = $UserModel->where('voucher','>','0')->where('platform_profit',1)->where('is_out', 1)->count();
//                    $members = $UserModel->where('voucher', '>', '0')->where('platform_profit', 1)->where('is_out', 1)->get()->toArray();
//                    foreach ($members as $k => $v) {
//                        if ($v['super_recommend'] == 0) {
//                            //分红上限
//                            $money = 495 * 2;
//                            if ($v['consumption_bonus'] > $money) {
//                                unset($members[$k]);
//                            }
//                        } elseif ($v['super_recommend'] == 1) {
//                            //分红上限
//                            $money = 495 * 2.2;
//                            if ($v['consumption_bonus'] > $money) {
//                                unset($members[$k]);
//                            }
//                        } elseif ($v['super_recommend'] == 2) {
//                            //分红上限
//                            $money = 495 * 2.4;
//                            if ($v['consumption_bonus'] > $money) {
//                                unset($members[$k]);
//                            }
//                        } elseif ($v['super_recommend'] == 3) {
//                            //分红上限
//                            $money = 495 * 2.6;
//                            if ($v['consumption_bonus'] > $money) {
//                                unset($members[$k]);
//                            }
//                        } elseif ($v['super_recommend'] == 4) {
//                            //分红上限
//                            $money = 495 * 2.8;
//                            if ($v['consumption_bonus'] > $money) {
//                                unset($members[$k]);
//                            }
//                        } else {
//                            //分红上限
//                            $money = 495 * 3;
//                            if ($v['consumption_bonus'] > $money) {
//                                $result = $UserModel->where('uid', $v['uid'])->update(['is_out' => 0, 'voucher' => 0, 'consumption_bonus' => 0, 'super_recommend' => 0]);
//                                $RecordTransaction = new RecordTransaction();
//                                if ($result) {
//                                    $recommendData = [
//                                        'uid' => $v['uid'],
//                                        'ordersn' => $ordersn,
//                                        'money' => 0,
//                                        'type' => 1,
//                                        'time' => time(),
//                                        'explain' => '已出局',
//                                        'remark' => '已出局',
//                                    ];
//                                    $RecordTransaction->add_transaction($recommendData);
//                                } else {
//                                    return ['code' => 0, 'data' => '分红失败'];
//                                }
//                                unset($members[$k]);
//                            }
//                        }
//                        $money2 = RETAIN_TWO($integral * $v['voucher']);
//                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
//                        //添加记录
//                        $v['credit2'] += $recommendMoney['money'];
//                        $v['credit5'] += $recommendMoney['redelivery'];
//                        $v['consumption_bonus'] += $money2;
//                        $v['achievement_increment'] = 0;
//                        //记录订单之前各会员的奖励币余额记录
//                        $res = $UserModel->where('uid', $v['uid'])->update(['credit2' => $v['credit2'], 'credit5' => $v['credit5'], 'consumption_bonus' => $v['consumption_bonus']]);
//                        //重新赋值
//                        $addData3['money'] = $money2;
//                        $addData3['text'] = '消费广告补贴';
//                        $addData3['remark'] = '消费广告补贴';
//                        $addData3['recommendMoney'] = $recommendMoney;
//                        $addData3['ordersn'] = $ordersn;
//                        if ($res) {
//                            $this->addOrder($v['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn'], $addData3['remark']);
//                        }
//                    }
//                }
//                //团队份额实时分红
//                if ($Poundage['set_order_consumption'] > 0) {
//                    $member_num = $UserModel->where('credit3', '>', '0')->where('platform_profit', 1)->sum('credit3');
//                    //单份份额
//                    $integrals = RETAIN_TWO(($order['price'] * $Poundage['set_order_team'] / 100) / $member_num);
//                    $members = $UserModel->where('credit3', '>', '0')->where('platform_profit', 1)->get()->toArray();
//                    foreach ($members as $k => $v) {
//                        $money2 = RETAIN_TWO($integrals * $v['credit3']);
//                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
//                        //添加记录
//                        $v['credit2'] += $recommendMoney['money'];
//                        $v['credit5'] += $recommendMoney['redelivery'];
//                        $v['team_bonus'] += $money2;
//                        $v['team_achievement'] = 0;
//                        //记录订单之前各会员的奖励币余额记录
//                        $res = $UserModel->where('uid', $v['uid'])->update(['team_achievement' => 0, 'credit2' => $v['credit2'], 'credit5' => $v['credit5'], 'team_bonus' => $v['team_bonus']]);
//                        //重新赋值
//                        $addData3['money'] = $money2;
//                        $addData3['type'] = 5;
//                        $addData3['text'] = '团队广告补贴';
//                        $addData3['remark'] = '团队广告补贴';
//                        $addData3['recommendMoney'] = $recommendMoney;
//                        $addData3['ordersn'] = $ordersn;
//                        if ($res) {
//                            $this->addOrder($v['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn'], $addData3['remark']);
//
//                        }
//                    }
//                }
//                $userNumber = Members::where('uid',$data['uid'])->value('stores_number');
//                if (!empty($userNumber)) {
//                    $store = StoresCenter::where('number',$userNumber)->first();
//                    $user = Members::where('uid',$data['uid'])->first();
//                    $storeUid = StoresCenter::where('number', $userNumber)->value('uid');
//                    //增加一条终身绑定门店个人账户奖励币增加的记录
//                    $firstUidTransactionData = [
//                        'uid' => $storeUid,
//                        'ordersn' => $order['ordersn'],
//                        'money' => RETAIN_TWO($goods['costprice'] * $Poundage['bind_store']/100),
//                        'type' => 5,
//                        'time' => time(),
//                        'explain' => '复销商城',
//                        'remark' => '终生绑定门店收益'
//                    ];
//                    $StoreFirstTransaction = $RecordTransaction->add_transaction($firstUidTransactionData);
//                    if (!$StoreFirstTransaction) {
//                        DB::rollback();  //回滚
//                        return ['code' => 0, 'data' => '终身绑定门店个人账户奖励币记录增加失败！'];
//                    }
//
//                    $firstSource = "姓名为" . $user["user_name"] . "，电话号码为" . $user["phone"] . "的用户在服务中心为手机号" . $store['phone'] . "进行了会员报单，共" . $goods['rulingprice'] . "元";
//
//                    $firstSourceStore = "姓名为" . $user["user_name"] . "，电话号码为" . substr_replace($user["phone"], '****', 3, 4) . "的用户在服务中心为手机号" . $store['phone'] . "进行了会员报单，共" . $goods['rulingprice'] . "元";
//
//                    $firstStoreCurrency = RETAIN_TWO($goods['costprice'] * $Poundage['bind_store']/100);
//
//                    $firstStoreNumber = $userNumber;
//
//                    //插入一条终身绑定门店返币收益记录
//                    $firstStoreProfitRecord = $StoresProfitRecordModel->add(['store_number' => $firstStoreNumber, 'currency' => $firstStoreCurrency, 'source' => $firstSource, 'source_store' => $firstSourceStore, 'addtime' => time(), 'profit_type' => 1, 'consum_type' => 1, 'ordersn' => $order['ordersn']]);
//                    if (!$firstStoreProfitRecord) {
//                        DB::rollback();  //回滚
//                        return ['code' => 0, 'data' => '终身绑定门店收益记录添加失败！'];
//                    }
//                }
//                //全国门店加权分润
//                $stores = StoresCenter::where('type',1)->get()->toArray();
//                if (!empty($stores)){
//                    $storeCount = count($stores);
//                    $storeMoney = RETAIN_TWO($goods['costprice'] * $Poundage['store_platform']/100/$storeCount);
//                    foreach ($stores as $k => $v){
//                        $storeMember = Members::where('uid',$v['uid'])->select('credit1', 'credit2', 'credit3', 'credit4', 'credit5')->first();
//                        $recommendMoney = CALCULATE($Poundage, $storeMoney, 2);
//                        //扣除平台费和复投币
//                        $storeMember['credit2'] += $recommendMoney['money'];
//                        $storeMember['credit5'] += $recommendMoney['redelivery'];
//                        //添加记录
//                        $this->addOrder($v['uid'], $storeMoney, 5, '全国服务中心分润', $recommendMoney, 0, $order['ordersn']);
//                        //更新会员数据
//                        $UserModel->where(['uid' => $v['uid']])->update($storeMember['attributes']);
//                    }
//                }
                DB::commit();
                return ['code' => 1, 'data' => '升单成功'];
                break;
            case 'addAddress'://添加会员收货地址
                $memberNewAddressData = [
                    'uid' => $data['data']['uid'],
                    'phone' => $data['data']['phone'],
                    'name' => $data['data']['name'],
                    'province' => $data['data']['province'],
                    'city' => $data['data']['city'],
                    'district' => $data['data']['district'],
                    'address' => $data['data']['address'],
                    'default' => 0,
                    'updated_at' => date('Y-m-d H:i:s'),
                    'created_at' => date('Y-m-d H:i:s'),];
                $addressMolde = new Address();
                $AddressId = $addressMolde->insertGetId($memberNewAddressData);
                if ($AddressId) {
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;

        }

    }

    /**
     * 业绩管理奖励
     * @param null $uid
     * @param null $referrer
     * @param array $Poundage
     * @param null $money
     * @param int $company_id
     * @param string $upgrade
     * @param string $ordersn
     */
    public function bonusAchievement($uid = null, $referrer = null, $Poundage = array(), $money = null, $company_id = 0, $upgrade = '', $ordersn = '')
    {
        //会员表
        $puid = $uid;
        $user = session('home_user');
        $share = $referrer;//分享人ID
        //业绩设置
        $QualityModel = new SetQuality();
        $Quality = $QualityModel->get()->toArray();
        $referrer = $referrer; //分享人
        $UserModel = new Members();
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $money6 = $money;
        $money7 = $money;
        $money8 = $money;
        $money9 = $money;
        $number3 = 1;
        $number4 = 1;
        $number5 = 1;
        $number6 = 1;
        $number7 = 1;
        $number8 = 1;
        $number9 = 1;
        $userInfor = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')
            ->select(
                'uid', 'referrer', 'level', 'level_name', 'level_grade',
                'credit1', 'credit2', 'credit5', 'type', 'super_recommend',
                'super_team_count', 'super_small_team_count', 'super_level',
                'super_level_name'
            )
            ->get()
            ->toArray();
        foreach ($userInfor as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {
//                  //寻找上级id 微客
                    $referrer = $v['referrer'];
                    //V1 一阶段奖励
                    if (($v['level'] == 1 && $v['level_grade'] >= 1) || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 1])->first();
                        if ($number3 <= 2) {
                            if ($number3 == 1) {
                                $money3 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                $number3++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money3, 5, 'V1业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money3 = RETAIN_TWO($money3 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                $number3++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money3, 5, 'V1业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V1 二阶段奖励
                    if ($v['level'] == 1 && $v['level_grade'] >= 2 || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 2])->first();
                        if ($number4 <= 2) {
                            if ($number4 == 1) {
                                $money4 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                $number4++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money4, 5, 'V1业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money4 = RETAIN_TWO($money4 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                $number4++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money4, 5, 'V1业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }

                    }
                    //V1 三阶段奖励
                    if ($v['level'] == 1 && $v['level_grade'] >= 3 || $v['level'] > 1) {
                        $set = SetQuality::where(['level' => 1, 'level_stage' => 3])->first();
                        if ($number5 <= 2) {
                            if ($number5 == 1) {
                                $money5 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                $number5++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money5, 5, 'V1业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money5 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                $number5++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money5, 5, 'V1业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }

                    }
                    //V2 一阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 1 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 1])->first();
                        if ($number6 <= 2) {
                            if ($number6 == 1) {
                                $money6 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                $number6++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money6, 5, 'V2业绩分享奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money6 = RETAIN_TWO($money6 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                $number6++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money6, 5, 'V2业绩管理奖(一阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V2 二阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 2 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 2])->first();
                        if ($number7 <= 2) {
                            if ($number7 == 1) {
                                $money7 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                $number7++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money7, 5, 'V2业绩分享奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money7 = RETAIN_TWO($money7 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                $number7++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money7, 5, 'V2业绩管理奖(二阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V2 三阶段奖励
                    if ($v['level'] == 2 && $v['level_grade'] >= 3 || $v['level'] > 2) {
                        $set = SetQuality::where(['level' => 2, 'level_stage' => 3])->first();
                        if ($number8 <= 2) {
                            if ($number8 == 1) {
                                $money8 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                $number8++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money8, 5, 'V2业绩分享奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money8 = RETAIN_TWO($money8 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                $number8++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money8, 5, 'V2业绩管理奖(三阶段)', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                    //V3 业绩奖励
                    if ($v['level'] >= 3) {
                        $set = SetQuality::where(['level' => 3])->first();
                        if ($number9 <= 2) {
                            if ($number9 == 1) {
                                $money9 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                $number9++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money9, 5, 'V3业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                }
                            } else {
                                $money9 = RETAIN_TWO($money9 * ($set['flat'] * 0.01));
                                $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                $number9++;
                                //添加记录
                                if ($v['type'] == 1 && $set['changer'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $ordersn);
                                    $this->addOrder($v['uid'], $money9, 5, 'V3业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                }
                            }
                        }
                    }
                }
            }
            //更新会员数据
            $UserModel->where(['uid' => $v['uid']])->update($v);
        }
        return true;
    }

    /**
     * @param $uid
     * 统计个人及团队累计数据
     */
    public function statistics($uid)
    {
        $othersUid = array();
        $team = array();
        $othersUid[] = $uid;
        $teamAchievement = 0;
        $times = 0;
        $achievement_increment = 0;
        do {
            $memberList = Members::whereIn('referrer', $othersUid)->select('uid', 'referrer')->get()->toArray();
            if ($memberList) {
                unset($othersUid);
                foreach ($memberList as $k => $v) {
                    $team[] = $v['uid'];
                    $othersUid[] = $v['uid'];
                }
            }
        } while (!empty($memberList));

        if (!empty($team)) {
            foreach ($team as $k => $v) {
                $user = Members::where('uid', $v)->select('single_achievement', 'day_times', 'day_achievement')->first();
                $teamAchievement += $user['single_achievement'];//团队业绩
                $times += $user['day_times'];//团队参与局数
                $achievement_increment += $user['day_achievement'];//团队新增业绩
            }
            $res = Members::where('uid', $uid)->update(['team_achievement' => $teamAchievement, 'team_numbers' => $times, 'achievement_increment' => $achievement_increment]);
            if ($res) {
                return ['code' => 1, 'data' => '统计个人业绩成功'];
            } else {
                return ['code' => 0, 'data' => '统计失败'];
            }
        } else {
            return ['code' => 0, 'data' => '暂无个人团队'];
        }


    }

    /*
     * 会员登陆审核列表
     */

    public function user_examine()
    {

        return view('Admin.user.examine');
    }

    /**
     * 会员审核列表
     */
    public function examine(Request $request)
    {

        $data = $request->all();
        switch ($data['class']) {
            //赠送商城申请列表
            case 'select':
                //关键字
                $keyword = empty($data['keyword']) ? 0 : $data['keyword'];
                $applyData = IdentityVerification::select();


                //状态
                if (isset($keyword['status'])) {
                    $applyData = $applyData->where('status', $keyword['status']);
                }
                //关键字
                if (!empty($keyword['keyword'])) {
                    $applyData = $applyData->where('name', 'like', '%' . $keyword['keyword'] . '%')->orWhere('phone', 'like', '%' . $keyword['keyword'] . '%')->orWhere('user_name', 'like', '%' . $keyword['keyword'] . '%');
                }
                //分页
                $applyData = $applyData->orderBy('id', 'desc')->paginate(15);
                if ($applyData) {
                    return ['code' => 1, 'data' => $applyData];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            //审核
            case 'edit':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $res = IdentityVerification::where('id', $data['id'])->first();
                    if ($res['status'] == 0) {
                        $data['status'] = 1;
                    }
//                    if ($res['status'] == 1) {
//                        $data['status'] = 3;
//                    }
                    $data['auditor'] = $adminUser->name;
                    $data['audit_time'] = date('Y-m-d H:i:s', time());
                    $apply = IdentityVerification::where('id', $data['id'])->update(array_only($data, ['status', 'auditor', 'audit_time']));
                    if ($apply) {
                        $save = Members::where('uid', $res['uid'])->increment('credit1', $res['recharge_money']);
                        if ($save) {
//                            交易记录
                            $RecordTransaction = new RecordTransaction();
                            $recommendData = [
                                'uid' => $res['uid'],
                                'ordersn' => $res['number'],
                                'money' => $res['recharge_money'],
                                'type' => 4,
                                'time' => time(),
                                'created_at' => date('Y-m-d H:i:s'),
                                'updated_at' => date('Y-m-d H:i:s'),
                                'explain' => '购物积分充值',
                                'remark' => '个人购物积分充值：' . $res['recharge_money'],
                            ];
                            $TransactionId = $RecordTransaction->insertGetId($recommendData);
                            //充值记录
                            $RecordRecharge = new RecordrRecharge();
                            $rechargeData = [
                                'uid' => $res['uid'],
                                'tid' => $TransactionId,
                                'money' => $res['recharge_money'],
                                'type' => 1,
                                'createtime' => time(),
                                'credit' => '购物积分充值',
                                'operator' => Auth::user()->user_name,
                                'remark' => '个人购物积分充值：' . $res['recharge_money'],
                            ];
                            $rechargeId = $RecordRecharge->create($rechargeData);

                            if ($rechargeId) {
                                return ['code' => 1, 'data' => '充值成功'];
                            } else {
                                return ['code' => 0, 'data' => '没有数据'];
                            }
                        }
                    }


                }
                break;
            //拒绝
            case 'reEdit':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $data['status'] = 2;
                    $data['auditor'] = $adminUser->user_name;
                    $data['audit_time'] = date('Y-m-d H:i:s', time());
                    $apply = IdentityVerification::where('id', $data['id'])->update(array_only($data, ['status', 'auditor', 'audit_time']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '已拒绝'];
                    } else {
                        return ['code' => 0, 'data' => '没有数据'];
                    }
                }
                break;
            //开通
            case 'back':
                if ($data['id']) {
                    $check = IdentityVerification::where('id', $data['id'])->first();
                    $data['status'] = 1;
                    $adminUser = Auth::user();
                    $data['auditor'] = $adminUser->user_name;
                    $data['audit_time'] = date('Y-m-d H:i:s', time());
                    $apply = IdentityVerification::where('id', $data['id'])->update(array_only($data, ['status', 'auditor', 'audit_time']));
                    $save = Members::where('uid', $check['uid'])->update(['type' => 1]);
                    if ($apply && $save) {
                        return ['code' => 1, 'data' => '开通成功'];
                    } else {
                        return ['code' => 0, 'data' => '没有数据'];
                    }
                }
                break;
        }
    }


    /**
     * 报单商城升级处理
     * @param $v 会员数据
     * @param $puid 上级会员
     * @param $ExceedShop 超级商城设置
     * @param $Quality 商城业绩设置
     * @return mixed 返回会员数据
     */

    public function UpGrade($v, $puid, $Quality, $array = array(), $share, $points)
    {
        $v['super_team_count'] += $points;
        $v['team_member_count'] += 1;
        //添加小区团队
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {  //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {//判断是否已有这个会员的业绩
                    $super_small_team_count[$puid] = [
                        'key' => $puid,
                        'val' => 1,
                        'money' => $points,
                    ];

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] += $points;
                    $super_small_team_count[$items]['val'] += 1;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);

        } else {
            $team_count = [
                $puid => [
                    'key' => $puid,
                    'val' => 1,
                    'money' => $points,
                ]
            ];

            $super_small_team_count = json_encode($team_count);
        }
        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        /*--------------------------------------**/
        //直推人数查询
        $realTeamCount = Members::where(['referrer' => $v['uid']])->select('uid')->count();
        $v['super_recommend'] = $realTeamCount;
        if ($v['level'] == 0) {  //v1
            if ($v['achievement'] >= $Quality[0]['consumption']) {
                $v['level_name'] = $Quality[0]['level_name'];
                $v['level'] = $Quality[0]['level'];
                $v['level_grade'] = $Quality[0]['level_stage'];
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[1]['team_count'] && $v['achievement'] >= $Quality[1]['consumption']) {
                    $v['level_grade'] = $Quality[1]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[2]['team_count'] && $v['achievement'] >= $Quality[2]['consumption']) {
                    $v['level_grade'] = $Quality[2]['level_stage'];
                }
            }

        }

        if ($v['level'] == 1 && $v['level_grade'] == 3) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[3]['team_count'] && $v['achievement'] >= $Quality[3]['consumption']) {
                    $v['level_grade'] = $Quality[3]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 4) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[4]['team_count'] && $v['achievement'] >= $Quality[4]['consumption']) {
                    $v['level_name'] = $Quality[4]['level_name'];
                    $v['level'] = $Quality[4]['level'];
                    $v['level_grade'] = $Quality[4]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 5) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[5]['team_count'] && $v['achievement'] >= $Quality[5]['consumption']) {
                    $v['level_name'] = $Quality[5]['level_name'];
                    $v['level'] = $Quality[5]['level'];
                    $v['level_grade'] = $Quality[5]['level_stage'];
                }
            }
        }

        if ($v['level'] == 1 && $v['level_grade'] == 6) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($v['super_team_count'] >= $Quality[6]['team_count'] && $v['achievement'] >= $Quality[6]['consumption']) {
                    $v['level_name'] = $Quality[6]['level_name'];
                    $v['level'] = $Quality[6]['level'];
                    $v['level_grade'] = $Quality[6]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 1) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[7]['small_team_count'] && $v['achievement'] >= $Quality[7]['consumption']) {
                    $v['level_grade'] = $Quality[7]['level_stage'];
                }
            }
        }

        if ($v['level'] == 2 && $v['level_grade'] == 2) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {
                //重组数组
                $arrSort = array();
                foreach ($super_small_team_count as $uniqid => $row) {
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                //排序 倒序
                array_multisort($arrSort['money'], constant('SORT_DESC'), $super_small_team_count);
                $counts = 0; //小区人数
                $big_num = 0; //大区人数
                foreach ($super_small_team_count as $items => $item) {
                    //计算大小区
                    if ($big_num > 0) {
                        $counts += $item['money'];
                    } else {
                        $big_num = $item['money'];
                    }
                }
                if ($counts >= $Quality[8]['small_team_count'] && $v['achievement'] >= $Quality[8]['consumption']) {
                    $v['level_name'] = $Quality[8]['level_name'];
                    $v['level'] = $Quality[8]['level'];
                    $v['level_grade'] = $Quality[8]['level_stage'];
                }
            }
        }
        return $v;
    }
    public function downGrade($v, $puid, $share, $money)
    {
        $v['super_team_count'] -= $money;
        $v['achievement'] -= $money;
        //添加小区团队
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {  //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {//判断是否已有这个会员的业绩
                    $super_small_team_count[$puid] = [
                        'key' => $puid,
                        'val' => 1,
                        'money' => $money,
                    ];

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] -= $money;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);

        } else {
            $team_count = [
                $puid => [
                    'key' => $puid,
                    'val' => 1,
                    'money' => $money,
                ]
            ];

            $super_small_team_count = json_encode($team_count);
        }
        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        return $v;
    }

    //会场会员信息收集
    public function collectMessage()
    {
        return view('Admin.collectMessage');
    }

    //会场会员信息
    public function getMessages(Request $request)
    {
        $data = $request->all();
        $data['keyword'] = empty($data['keyword']) ? "" : $data['keyword'];
        $messageModel = new FieldActivities();
        switch ($data['class']) {
            case 'select': //订单列表
                $messageModel = $messageModel->distinct()->orderBy('id', 'desc');
                if (!empty($data['keyword']['createtime'])) {
                    $messageModel = $messageModel->where('createtime', '>', strtotime($data['keyword']['createtime'][0]))->where('createtime', '<', strtotime($data['keyword']['createtime'][1]));
                }
                if (!empty($data['keyword']['keyword'])) {
                    $messageModel = $messageModel->where(function ($messageModel) use ($data) {
                        $messageModel->where('name', 'like', '%' . $data['keyword']['keyword'] . '%')->orWhere('phone', $data['keyword']['keyword']);
                    });
                }

                $messageData = $messageModel->get()->toArray();

                $rico = $messageModel->paginate(15);
                foreach ($rico as $k => $value) {
                    $rico[$k]['createtime'] = date('Y-m-d H:i:s', $value->createtime);
                }

                if ($rico) {
                    return ['code' => 1, 'data' => $rico];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
        }
    }

    /**
     * * 报单商城奖金计算
     * @param null $uid
     * @param null $referrer
     * @param array $ExceedShop
     * @param array $Quality
     * @param int $grade_type
     * @param array $Poundage
     * @param null $money
     * @param string $ordersn
     * @param int $type
     * @return bool
     */
    public function superShop($uid = null, $referrer = null, $Quality = array(), $grade_type = 1, $Poundage = array(), $points = null, $ordersn = '', $money = null, $setBonus = array())
    {
        //会员表
        $type = 0;
        $company_id = 0;
        $UserModel = new Members();
        $userApply = new Apply();
        //超级商城设置
        $ExceedShopModel = new ExceedShop();
        $ExceedShop = $ExceedShopModel->where(['id' => 1])->first();
        $order = ShopOrder::where('ordersn', $ordersn)->first();
        $address = Address::where('id', $order['addressid'])->first();
        //查询该区域代理
        //查询市代理
        $cityData = $userApply->where(['type' => 1, 'city' => $address['city'], 'status' => 1])->get()->toArray();
        $agencyCity = 0;//市代理uid
        if (!empty($cityData)) {
            foreach ($cityData as $k => $v) {
                $district = json_decode($v['district'], true);
                if ($district) {
                    $district = explode(",", $district);
                    if (in_array($address['district'], $district)) {
                        $agencyCity = $v['uid'];
                    }
                }
            }
        }
        $city = $address['city'] . $address['district'];
        $bonusLevel = 0;//奖励等级
        $share = $referrer;//分享人ID
        $puid = $uid;
//        $achive = ShopOrder::where('ordersn',$ordersn)->value('price');
        $money1 = $money;
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $money6 = $money;
        $money7 = $money;
        $money8 = $money;
        $money9 = $money;
        $money10 = $money;
        $money11 = $money;
        $money12 = $money;
        $number1 = 1;
        $number3 = 1;
        $number4 = 1;
        $number5 = 1;
        $number6 = 1;
        $number7 = 1;
        $number8 = 1;
        $number9 = 1;
        $number10 = 1;
        $number11 = 1;
        $number12 = 1;
        $ricos = 1; //判断错误
        $arrays = [];
        $members = $UserModel->where('uid', '<=', $uid)->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();

        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {    //寻找上级id 微客
                    $referrer = $v['referrer'];
                    //会员等级升级

                    $arrays[$v['uid']] = $v['referrer'];
                    $v = $this->UpGrade($v, $puid, $Quality, $arrays, $share, $points);
                    //直推奖励
                    if ($ExceedShop['vip'] > 0 && $money > 0) {
                        if ($v['super_level'] >= 1) {
                            if ($number1 == 1) {
                                $money1 = RETAIN_TWO($money * ($ExceedShop['vip'] * 0.01));
                                if ($v['uid'] < 546) {
                                    $recommendMoney = CALCULATQ($Poundage, $money1, 1);
                                } else {
                                    $recommendMoney = CALCULATE($Poundage, $money1, 1);
                                }
                                $number1++;
                                //添加记录
                                if ($v['type'] == 1) {
                                    $v['credit2'] += $recommendMoney['money'];
                                    $v['credit5'] += $recommendMoney['redelivery'];
                                    $this->bonusCredit2($v['uid'], $order['ordersn']);
                                    $this->addOrder($v['uid'], $money1, 5, '报单直推奖', $recommendMoney, $company_id, $order['ordersn']);
                                }
                            }
                        }
                    }
                    if ($money > 0) {
                        //V1 一阶段奖励
                        if ($v['level'] >= 1) {
                            $set = SetQuality::where(['level' => 1])->first();
                            if ($number3 <= 2) {
                                if ($number3 == 1) {
                                    $money3 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                    $number3++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money3, 5, 'V1业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money3 = RETAIN_TWO($money3 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money3, 1);
                                        $number3++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money3, 5, 'V1业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }
                        }
                        //V1 二阶段奖励
                        if ($v['level'] >= 2) {
                            $set = SetQuality::where(['level' => 2])->first();
                            if ($number4 <= 2) {
                                if ($number4 == 1) {
                                    $money4 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                    $number4++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money4, 5, 'V2业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money4 = RETAIN_TWO($money4 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money4, 1);
                                        $number4++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money4, 5, 'V2业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }
                                }
                            }

                        }
                        //V1 三阶段奖励
                        if ($v['level'] >= 3) {
                            $set = SetQuality::where(['level' => 3])->first();
                            if ($number5 <= 2) {
                                if ($number5 == 1) {
                                    $money5 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                    $number5++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money5, 5, 'V3业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money5 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money5, 1);
                                        $number5++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money5, 5, 'V3业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V1 四阶段奖励
                        if ($v['level'] >= 4) {
                            $set = SetQuality::where(['level' => 4])->first();
                            if ($number8 <= 2) {
                                if ($number8 == 1) {
                                    $money8 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                    $number8++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money8, 5, 'V4业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    if ($set['flat'] > 0) {
                                        $money8 = RETAIN_TWO($money5 * ($set['flat'] * 0.01));
                                        $recommendMoney = CALCULATE($Poundage, $money8, 1);
                                        $number8++;
                                        //添加记录
                                        if ($v['type'] == 1 && $set['changer'] == 1) {
                                            $v['credit2'] += $recommendMoney['money'];
                                            $v['credit5'] += $recommendMoney['redelivery'];
                                            $this->bonusCredit2($v['uid'], $ordersn);
                                            $this->addOrder($v['uid'], $money8, 5, 'V4业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                        }
                                    }

                                }
                            }

                        }
                        //V2 一阶段奖励
                        if ($v['level'] >= 5) {
                            $set = SetQuality::where(['level' => 5])->first();
                            if ($number6 <= 2) {
                                if ($number6 == 1) {
                                    $money6 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V5业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money6 = RETAIN_TWO($money6 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money6, 1);
                                    $number6++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money6, 5, 'V5业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 二阶段奖励
                        if ($v['level'] >= 6) {
                            $set = SetQuality::where(['level' => 6])->first();
                            if ($number7 <= 2) {
                                if ($number7 == 1) {
                                    $money7 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V6业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money7 = RETAIN_TWO($money7 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money7, 1);
                                    $number7++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money7, 5, 'V6业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        //V2 三阶段奖励
                        if ($v['level'] >= 7) {
                            $set = SetQuality::where(['level' => 7])->first();
                            if ($number9 <= 2) {
                                if ($number9 == 1) {
                                    $money9 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V7业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money9 = RETAIN_TWO($money9 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money9, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money9, 5, 'V7业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        if ($v['level'] >= 8) {
                            $set = SetQuality::where(['level' => 7])->first();
                            if ($number10 <= 2) {
                                if ($number10 == 1) {
                                    $money10 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money10, 1);
                                    $number10++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money10, 5, 'V8业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money10 = RETAIN_TWO($money10 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money10, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money10, 5, 'V8业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        if ($v['level'] >= 9) {
                            $set = SetQuality::where(['level' => 7])->first();
                            if ($number11 <= 2) {
                                if ($number11 == 1) {
                                    $money11 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money11, 1);
                                    $number11++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money11, 5, 'V9业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money11 = RETAIN_TWO($money11 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money11, 1);
                                    $number9++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money11, 5, 'V9业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                        if ($v['level'] >= 10) {
                            $set = SetQuality::where(['level' => 7])->first();
                            if ($number12 <= 2) {
                                if ($number12 == 1) {
                                    $money12 = RETAIN_TWO($money * ($set['reword'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money12, 1);
                                    $number12++;
                                    //添加记录
                                    if ($v['type'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money12, 5, 'V10业绩分享奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                } else {
                                    $money12 = RETAIN_TWO($money12 * ($set['flat'] * 0.01));
                                    $recommendMoney = CALCULATE($Poundage, $money12, 1);
                                    $number12++;
                                    //添加记录
                                    if ($v['type'] == 1 && $set['changer'] == 1) {
                                        $v['credit2'] += $recommendMoney['money'];
                                        $v['credit5'] += $recommendMoney['redelivery'];
                                        $this->bonusCredit2($v['uid'], $ordersn);
                                        $this->addOrder($v['uid'], $money12, 5, 'V10业绩管理奖', $recommendMoney, $company_id, $ordersn);
                                    }
                                }
                            }
                        }
                    }

                    $puid = $v['uid'];
                    //更新会员数据
                    if ($UserModel->where(['uid' => $v['uid']])->update(
                        [
                            'credit1' => $v['credit1'],
                            'credit2' => $v['credit2'],
                            'credit5' => $v['credit5'],
                            'level' => $v['level'],
                            'level_name' => $v['level_name'],
                            'level_grade' => $v['level_grade'],
                            'super_recommend' => $v['super_recommend'],
                            'team_member_count' => $v['team_member_count'],
                            'super_team_count' => $v['super_team_count'],
                            'super_small_team_count' => $v['super_small_team_count'],
                            //                            'super_level' => $v['super_level'],
                            //                            'super_level_name' => $v['super_level_name'],

                        ]
                    )
                    ) {
                        //添加记录
                        if (!empty($v['addData']['addData1'])) {
                            $this->addOrder($v['uid'], $v['addData']['addData1']['money'], 5, $v['addData']['addData1']['text'], $v['addData']['addData1']['recommendMoney'], 0, $v['addData']['addData1']['ordersn']);
                        }

                    } else {

                        return false;
                    }

                }
            }
        }
//        代理奖励分配
        $this->bonusAgency($agencyCity, $money, $Poundage, $ordersn, $city);
        return true;
    }

    /**
     * 代理奖励分配
     * @param $agencyArea
     * @param $agencyCity
     * @param $money
     * @param $Poundage
     * @param $ordersn
     */
    public function bonusAgency($agencyCity, $money, $Poundage, $ordersn, $city)
    {
        $money1 = $money;
        $money2 = $money;
        $money3 = $money;
        $money4 = $money;
        $money5 = $money;
        $UserModel = new Members();
        if (!empty($agencyCity)) {//市代理奖励
            $apply_id = Apply::where('uid', $agencyCity)->value('id');
            $partners = SetRebate::where(['a_id' => $apply_id, 'is_partner' => 1, 'status' => 1])->get()->toArray();
            $service = SetRebate::where(['a_id' => $apply_id, 'is_service' => 1, 'status' => 1])->get()->toArray();
            $ceo = SetRebate::where(['a_id' => $apply_id, 'is_ceo' => 1, 'status' => 1])->get()->toArray();
            $investment = SetRebate::where(['a_id' => $apply_id, 'is_investor' => 1, 'status' => 1])->get()->toArray();
            $ser_count = count($service);
            $count = count($partners);
            $ceo_count = count($ceo);
            $invest_count = count($investment);
            if ($count == 0) {
                $Poundage['distribution'] = 0;
            }
            if ($ser_count == 0) {
                $Poundage['platform_profit'] = 0;
            }
            if ($ceo_count == 0) {
                $Poundage['ceo'] = 0;
            }
            if ($invest_count == 0) {
                $Poundage['investment'] = 0;
            }

            //添加合伙人分红
            if ($Poundage['distribution'] > 0) {
                if ($count > 0) {
                    foreach ($partners as $k => $v) {
                        $partner = Members::where('name', $v['name'])->first();
                        $money2 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['distribution'] / 100 / $count);
                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
                        //添加记录
                        if ($partner['type'] == 1) {
                            $partner['credit2'] += $recommendMoney['money'];
                            $partner['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $partner['uid'])->update(['credit2' => $partner['credit2'], 'credit5' => $partner['credit5']]);
                            $this->credit2Record($ordersn, $partner['uid']);
                            //重新赋值
                            $addData3['money'] = $money2;
                            $addData3['type'] = 5;
                            $addData3['text'] = $city . '合伙人分润';
                            $addData3['recommendMoney'] = $recommendMoney;
                            $addData3['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($partner['uid'], $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
                            }
                        }
                    }
                }
            }

            //添加服务组分红
            if ($Poundage['platform_profit']) {
                if ($ser_count > 0) {
                    foreach ($service as $k => $v) {
                        $ser = Members::where('name', $v['name'])->first();
                        $money3 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['platform_profit'] / 100 / $ser_count);
                        $recommendMoney = CALCULATE($Poundage, $money3, 2);
                        //添加记录
                        if ($ser['type'] == 1) {
                            $ser['credit2'] += $recommendMoney['money'];
                            $ser['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $ser['uid'])->update(['credit2' => $ser['credit2'], 'credit5' => $ser['credit5']]);
                            $this->credit2Record($ordersn, $ser['uid']);
                            //重新赋值
                            $addData4['money'] = $money3;
                            $addData4['type'] = 5;
                            $addData4['text'] = $city . '运营分润';
                            $addData4['recommendMoney'] = $recommendMoney;
                            $addData4['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($ser['uid'], $addData4['money'], 5, $addData4['text'], $addData4['recommendMoney'], 0, $addData4['ordersn']);
                            }
                        }
                    }
                }
            }

            //添加区域CEO分红
            if ($Poundage['ceo'] > 0) {
                if ($ceo_count > 0) {
                    foreach ($ceo as $k => $v) {
                        $user = Members::where('name', $v['name'])->first();
                        $money4 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['ceo'] / 100 / $ceo_count);
                        $recommendMoney = CALCULATE($Poundage, $money4, 2);
                        //添加记录
                        if ($user['type'] == 1) {
                            $user['credit2'] += $recommendMoney['money'];
                            $user['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $user['uid'])->update(['credit2' => $user['credit2'], 'credit5' => $user['credit5']]);
                            $this->credit2Record($ordersn, $user['uid']);
                            //重新赋值
                            $addData5['money'] = $money4;
                            $addData5['type'] = 5;
                            $addData5['text'] = $city . '区域CEO分润';
                            $addData5['recommendMoney'] = $recommendMoney;
                            $addData5['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($user['uid'], $addData5['money'], 5, $addData5['text'], $addData5['recommendMoney'], 0, $addData5['ordersn']);
                            }
                        }
                    }
                }
            }

            //添加总务分红
            if ($Poundage['investment']) {
                if ($invest_count > 0) {
                    foreach ($investment as $k => $v) {
                        $invest = Members::where('name', $v['name'])->first();
                        $money5 = RETAIN_TWO(($Poundage['city']) * $money / 100 * $Poundage['investment'] / 100 / $invest_count);
                        $recommendMoney = CALCULATE($Poundage, $money5, 2);
                        //添加记录
                        if ($invest['type'] == 1) {
                            $invest['credit2'] += $recommendMoney['money'];
                            $invest['credit5'] += $recommendMoney['redelivery'];
                            //记录订单之前各会员的奖励币余额记录
                            $res = $UserModel->where('uid', $invest['uid'])->update(['credit2' => $invest['credit2'], 'credit5' => $invest['credit5']]);
                            $this->credit2Record($ordersn, $invest['uid']);
                            //重新赋值
                            $addData6['money'] = $money5;
                            $addData6['type'] = 5;
                            $addData6['text'] = $city . '总务分润';
                            $addData6['recommendMoney'] = $recommendMoney;
                            $addData6['ordersn'] = $ordersn;
                            if ($res) {
                                $this->addOrder($invest['uid'], $addData6['money'], 5, $addData6['text'], $addData6['recommendMoney'], 0, $addData6['ordersn']);
                            }
                        }
                    }
                }
            }
        }
    }

    public function setTeamCount()
    {
        $members = Members::get()->toArray();
        foreach ($members as $k => $v) {
            $super_small_team_count = json_decode($v['super_small_team_count'], true);
            if ($super_small_team_count) {  //判断是否已有团队业绩
                $teamCount = 0;
                foreach ($super_small_team_count as $items => $item) {
                    $teamCount += $item['val'];
                }
                Members::where('uid', $v['uid'])->update(['team_member_count' => $teamCount]);
            }
        }
        return 'OK';
    }

    public function findUsers()
    {
        //合伙人业绩撤回
//        $record = RecordTransaction::where(['ordersn' => 'M303769868125987','money' => 1.25])->get()->toArray();
//        DB::beginTransaction();
//        foreach ($record as $k => $v){
//            $user = Members::where('uid',$v['uid'])->first();
//            $res = Members::where('uid',$user['uid'])->update(['credit2' => ($user['credit2'] - 1.14),'credit5' => ($user['credit5'] - 0.08)]);
//            if (!$res){
//                DB::rollback();
//                return ['code' => 0,'data' => '撤回失败'];
//            }
//        }
//        DB::commit();
//        return ['code' => 1,'data' => '撤回成功'];
        //会员业绩导出
//        $teamMember = [];
//        $userId = 435;
//        $first = Members::where('referrer',$userId)->select('uid')->get()->toArray();
//        do {
//            $team = [];
//            foreach ($first as $k => $v){
//                $teamMember[] = $v['uid'];
//                $others = Members::where('referrer',$v['uid'])->select('uid')->get()->toArray();;
//                if (!empty($others)){
//                    $team = array_merge($team,$others);
//                }
//            }
//            $first = $team;
//        } while (!empty($first)
//        );
//        $orders = ShopOrder::whereIn('uid',$teamMember)->where('status','>=',2)->get()->toArray();
//        $newData[] = ['编号', '订单编号', '用户', '电话', '金额', '地址','交易时间', '备注'];
//        foreach ($orders as $k => $v){
//            $v['paytime'] = date('Y-m-d H:i:s',$v['paytime']);
//            $newData[] = [
//                $v['id'],
//                $v['ordersn'],
//                $v['receipt_name'],
//                $v['receipt_phone'],
//                $v['price'],
//                $v['receipt_adr'],
//                $v['paytime'],
//                $v['remark']
//            ];
//        }
//        Excel::create("余玲业绩明细", function ($excel) use ($newData) {
//            $excel->sheet('score', function ($sheet) use ($newData) {
//                $sheet->rows($newData);
//            });
//        })->export('xls');
//
//        return $orders;
        //老师业绩撤回
//        $type = 0;
//        $members = Members::where('uid', '<=', 	762)->orderBy('uid', 'desc')->select('uid', 'referrer','level','level_name', 'level_grade','credit1', 'credit2', 'credit3', 'credit4', 'credit5','team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement','team_profit')->get()->toArray();
//        $referrer = 681;
//        $arrays = [];
//        $share = $referrer;
//        foreach ($members as $k => $v) {
//            if (!empty($v['referrer'])) {
//                if ($referrer == $v['uid']) {//寻找上级id 微客
//                    $referrer = $v['referrer'];
//                    //会员等级升级
//                    if ($type == 0) {
//                        $arrays[$v['uid']] = $v['referrer'];
//                        $v = $this->downGrade($v, 	762, $share, 6000);
//                    }
//                    //上级uid
//                    $puid = $v['uid'];
//                    //更新会员数据
//                    Members::where(['uid' => $v['uid']])->update(
//                        [
//                            'credit1' => $v['credit1'],
//                            'credit2' => $v['credit2'],
//                            'credit3' => $v['credit3'],
//                            'credit4' => $v['credit4'],
//                            'credit5' => $v['credit5'],
//                            'level' => $v['level'],
//                            'level_name' => $v['level_name'],
//                            'super_recommend' => $v['super_recommend'],
//                            'super_team_count' => $v['super_team_count'],
//                            'super_small_team_count' => $v['super_small_team_count'],
//                            'super_level' => $v['super_level'],
//                            'super_level_name' => $v['super_level_name'],
//                            'is_credit3' => $v['is_credit3'],
//                            'achievement' => $v['achievement'],
//                        ]);
//
//
//                }
//            }
//        }
//        return 'ok';

    }

    /**
     * 订单撤回
     * @param Request $request
     * @return array
     */
    public function recallOrder(Request $request)
    {

        //系统设置
        $data = $request->all();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        $order = ShopOrder::where('id', $data['order_id'])->first();
        //订单奖励撤回
        $record = RecordTransaction::where(['id' => $data['order_id']])->get()->toArray();
        DB::beginTransaction();
        foreach ($record as $k => $v) {
            $user = Members::where('uid', $v['uid'])->first();
            if ($v['type'] == 5) {
                $bonus = RecordBonus::where('tid', $v['id'])->first();
                $credit2 = RETAIN_TWO($bonus['money'] * (100 - $Poundage['redelivery'] - $Poundage['platform_fee']) / 100);
                $credit5 = RETAIN_TWO($bonus['money'] * $Poundage['redelivery'] / 100);
                $res = Members::where('uid', $user['uid'])->update(['credit2' => ($user['credit2'] - $credit2), 'credit5' => ($user['credit5'] - $credit5)]);
                if (!$res) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '撤回失败'];
                }
            } else {
                $res = Members::where('uid', $user['uid'])->update(['credit2' => ($user['credit2'] + $v['money'])]);
                if (!$res) {
                    DB::rollback();
                    return ['code' => 0, 'data' => '撤回失败'];
                }
            }
        }
        //订单业绩
        $orderComment = ShopOrderComment::where(['orderid' => $data['order_id']])->get()->toArray();
        $cost_price = 0;
        foreach ($orderComment as $k => $v) {
            $cost = ShopGoods::where('id', $v['goodsid'])->value('costprice');
            $cost_price += $v['number'] * $cost;
        }
        //老师业绩撤回
        $type = 0;
        $members = Members::where('uid', '<=', $order['uid'])->orderBy('uid', 'desc')->select('uid', 'referrer', 'level', 'level_name', 'level_grade', 'credit1', 'credit2', 'credit3', 'credit4', 'credit5', 'team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement', 'team_profit')->get()->toArray();
        $referrer = Members::where('uid', $order['uid'])->value('referrer');
        $arrays = [];
        $share = $referrer;
        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {//寻找上级id 微客
                    $referrer = $v['referrer'];
                    //会员业绩撤回
                    if ($type == 0) {
                        $arrays[$v['uid']] = $v['referrer'];
                        $v = $this->downGrade($v, $order['uid'], $share, $cost_price);
                    }
                    //上级uid
                    $puid = $v['uid'];
                    //更新会员数据
                    Members::where(['uid' => $v['uid']])->update(
                        [
                            'credit1' => $v['credit1'],
                            'credit2' => $v['credit2'],
                            'credit3' => $v['credit3'],
                            'credit4' => $v['credit4'],
                            'credit5' => $v['credit5'],
                            'level' => $v['level'],
                            'level_name' => $v['level_name'],
                            'super_recommend' => $v['super_recommend'],
                            'super_team_count' => $v['super_team_count'],
                            'super_small_team_count' => $v['super_small_team_count'],
                            'super_level' => $v['super_level'],
                            'super_level_name' => $v['super_level_name'],
                            'is_credit3' => $v['is_credit3'],
                            'achievement' => $v['achievement'],
                        ]);


                }
            }
        }
        DB::commit();
        return ['code' => 1, 'data' => '撤回成功'];
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 总公司合伙人列表
     */

    public function company()
    {
        return view('Admin.company.index');
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 代理分公司合伙人列表
     */
    public function companyList(Request $request)
    {
        $data = $request->all();
        switch ($data['class']) {
            //代理合伙人列表
            case 'select':
                //关键字
                $keyword = empty($data['keyword']) ? 0 : $data['keyword'];
//                $applyModel = new SetrebateCompany();
                $applyData = SetrebateCompany::where('status', 1)
                    ->where(function ($query) use ($keyword) {
                        if (!empty($keyword['keyword'])) {
                            $query->where(function ($query) use ($keyword) {
                                $query->where('user_name', 'like', '%' . $keyword['keyword'] . '%')
                                    ->orWhere('name', 'like', '%' . $keyword['keyword'] . '%');
                            });
                        }
                    })
                    ->orderBy('id', 'desc')->paginate(15);
                if ($applyData) {
                    return ['code' => 1, 'data' => $applyData];
                } else {
                    return ['code' => 0, 'data' => '暂无数据'];
                }
                break;
            //代理合伙人是否存在系统
            case 'find_member': //删除
                if ($data['name']) {
                    $members = Members::where('name', $data['name'])->select('name', 'user_name')->first();
                    if ($members) {
                        return ['code' => 1, 'data' => $members];
                    } else {
                        return ['code' => 0, 'data' => '此系统暂无该会员'];
                    }
                }
                break;
            //代理合伙人申请
            case 'add':
                if (empty($data['name'])) {
                    return ['code' => 0, 'data' => '账号不能为空'];
                }
                if (empty($data['user_name'])) {
                    return ['code' => 0, 'data' => '姓名不能为空'];
                }
                $name = Members::where('name', $data['name'])->first();
                if (!$name) {
                    return ['code' => 0, 'data' => '此会员不存在'];
                }
                $members = SetrebateCompany::where(['name' => $data['name'], 'is_one' => $data['is_one'], 'status' => 1])->select('is_one')->first();
                if ($members) {
                    return ['code' => 0, 'data' => '此会员身份已存在'];
                }
                $members = SetrebateCompany::where(['name' => $data['name'], 'is_two' => $data['is_two'], 'status' => 1])->select('is_two')->first();
                if ($members) {
                    return ['code' => 0, 'data' => '此会员身份已存在'];
                }
                $members = SetrebateCompany::where(['name' => $data['name'], 'is_three' => $data['is_three'], 'status' => 1])->select('is_three')->first();
                if ($members) {
                    return ['code' => 0, 'data' => '此会员身份已存在'];
                }

                $adminUser = Auth::user();
                $data['information']['verifier'] = $adminUser->user_name;
                $data['information']['is_one'] = $data['is_one'];
                $data['information']['is_two'] = $data['is_two'];
                $data['information']['is_three'] = $data['is_three'];
                $data['information']['status'] = 1;
                $data['information']['name'] = $data['name'];
                $data['information']['user_name'] = $data['user_name'];
//                    $maxSort = SetrebateCompany::where(['a_id' => $data['id']])->max('sort');
//                    $data['information']['sort'] = empty($maxSort)?1:($maxSort + 1);
//                var_dump($data['information']);exit;
                $userRoic = SetrebateCompany::create($data['information']);
                if ($userRoic) {
                    return ['code' => 1, 'data' => '添加成功'];
                } else {
                    return ['code' => 0, 'data' => '添加失败'];
                }

                break;
            //代理查找
            case 'find':
                if ($data['id']) {
                    $members = SetrebateCompany::where('id', $data['id'])->select('name', 'user_name', 'is_one', 'is_two', 'is_three')->first();
                    if ($members) {
                        return ['code' => 1, 'data' => $members];
                    } else {
                        return ['code' => 0, 'data' => '暂无此会员信息'];
                    }
                }
                break;
            //代理合伙人编辑
            case 'edit':
                if (empty($data['name'])) {
                    return ['code' => 0, 'data' => '账号不能为空'];
                }
                if (empty($data['user_name'])) {
                    return ['code' => 0, 'data' => '姓名不能为空'];
                }
                $adminUser = Auth::user();
                $data['information']['verifier'] = $adminUser->user_name;
                $data['information']['is_one'] = $data['is_one'];
                $data['information']['is_two'] = $data['is_two'];
                $data['information']['is_three'] = $data['is_three'];
                $data['information']['name'] = $data['name'];
                $data['information']['user_name'] = $data['user_name'];
                $apply = SetrebateCompany::where('id', $data['id'])->update(array_only($data, ['verifier', 'is_one', 'is_two', 'is_three', 'name', 'user_name']));
                if ($apply) {
                    return ['code' => 1, 'data' => '编辑成功'];
                } else {
                    return ['code' => 0, 'data' => '编辑失败'];
                }

                break;
            //删除代理下合伙人
            case 'delete':
                if ($data['id']) {
                    $adminUser = Auth::user();
                    $data['verifier'] = $adminUser->user_name;
                    $data['status'] = -1;
                    $apply = SetrebateCompany::where('id', $data['id'])->update(array_only($data, ['status', 'verifier']));
                    if ($apply) {
                        return ['code' => 1, 'data' => '删除成功'];
                    } else {
                        return ['code' => 0, 'data' => '删除失败'];
                    }
                }


        }
    }

    /*
     * 我的团队
     */
    public function my_team(Request $request)
    {
        $data = $request->all();
        $UserModel = new Members();
        if (!empty($data['keyword']['keyword'])) {
            $table = $UserModel->where(['name' => $data['keyword']['keyword']])
                ->orWhere('user_name', 'like', '%' . $data['keyword']['keyword'] . '%');
            $members = $table->where('referrer', '=', $data['uid'])->orderBy('uid', 'desc')->paginate(20);
            foreach ($members as $v) {
                $v['enroll_time'] = date("Y-m-d H:i:s", $v['enroll_time']);
            }
            if ($members) {
                return ['code' => 1, 'data' => $members];
            } else {
                return ['code' => 0, 'data' => '暂无会员信息'];
            }
        } else {
            $members = $UserModel->where('referrer', '=', $data['uid'])->orderBy('uid', 'desc')->paginate(20);
            foreach ($members as $v) {
                $v['enroll_time'] = date("Y-m-d H:i:s", $v['enroll_time']);
            }
            if ($members) {
                return ['code' => 1, 'data' => $members];
            } else {
                return ['code' => 0, 'data' => '暂无团队'];
            }
        }


    }

}
